Array, String and Pointer in C Programming

An array is a data structure that store a number of data items as a single object. The individual data items inside an array are called elements and all of them have same data types. Array is used when multiple data items have common data types or similar characteristics .

One Dimensional Array

In one dimensional array, there is a single subscript or index whose value refers to the individual array element which ranges from 0 to (n-1). The first element of array is indexed zero, so the last element is one less than the size of the array.  

Declaration of One Dimensional Array

storage class(optional) data type array name(size);

Example: 

int  nums [5,4,3,2,1];

Accessing array elements

The particular array element in an array is accessed by specifying the name of array, followed by square bracket enclosing an integer, which is called array index. The array index indicates the particular element of the array we want to access.

nums[3] = 2

Multidimensional Array

Multi-dimensional arrays are defined in the same manner as one dimensional array except that a separate pair of square brackets is required for each dimension.

Declaration of multidimensional dimensional array:

data type array name [row number] [column number];

Example :

int nums a{
  {1,2,3}
  {4,5,6}
  {7,8,9}
}

Accessing Multidimensional Array

In multidimensional array, the first dimension specifies number of rows and second specifies the number of columns. Each row contains elements of many columns. Thus, multidimensional array is an array of one dimensional array.

nums[1,2] = 5

Passing Arrays To Function

It is possible to pass the value of an array element and even array as an argument to a function. To pass an entire array to a function, the array name must appear by itself without brackets or subscripts as an actual argument in function call statement.

Example : 

#include <stdio.h>

float average(int arr[], int size);

int main () {

   int balance[7] = {10,2,3,17,5,12,18};
   float avg;

   avg = average( balance, 7 ) ;

   printf( "Average value is: %f ", avg );
   return 0;
}

float average(int arr[], int size) {

   int i;
   float avg;
   float sum = 0;

   for (i = 0; i < size; ++i) {
      sum += arr[i];
   }

   avg = sum / size;

   return avg;
}

Characteristics of an Array

i. The declaration int balance[7] is simply 5 variables of integer types in the memory. Instead of declaring 5 variables for five values, the programmer can define them in array. The datatype given declares the nature of the elements of the array.
ii.    All elements of an array share same name and they are distinguished from one another with the help of an array index or element number.
iii. The array index plays an vital role for calling the elements of the array.
iv. Any particular element of an array can be modified separately without distributing other elements.
v. Any element of an array can be assigned to ordinary variable or array variables of it’s type. 

Strings

String is an array of characters (i.e characters are arranged one after another in the memory). A string is always terminated by a NULL character ('\0'). The terminating null characters is important because it is the only way for string handling functions to know the end of string. 

Initializing Strings

char name[] = "webtrickshome";
char name[]= {'w','e','b','t','r','i','c','k','s','h','o','m','e','\0'};

The characters of the string are enclosed within a pair of double quotes. It is important to note down that all strings must end with a null character(\0).

Array of Strings

String itself is an array of characters. Thus, an array of strings is a mulitidimensional array of characters. The array of string is declared as:

char name[size1][size2];

String Handling Functions

1. strlen()

The function strlen() receives a string of argument and returns an integer which represents the length of string passed. The length of string is the number of character present in it excluding the terminating null character. 

Example :

#include <stdio.h>

int main () 
{
  int count;
  char name[] = "webtrickshome";
  count = strlen(name);
  printf("The total number of alphabets here is %d\t",count);
  return 0;
}

2. strcpy()

This function copies one string to another. The function accepts two strings as parameters and copies the second string into the first string character by character including the null character.

Example :

#include <stdio.h>

int main () 
{
  char name[] = "webtrickshome";
  char type[] = "tutorials";
  
  strcpy(type,name);
  printf("The new text is %s\t",type);
  return 0;
}

3. strcat()

The strcat() function concatenates(joins) two strings into one string i.e. it appends one string at the end of the another string).

Example :

#include <stdio.h>

int main ()
{
  char name[] = "webtrickshome ";
  char type[] = "tutorials";

  printf("The new string is %s\n",strcat(name,type));
}

4. strcmp()

The strcmp() function compares two strings and find out whether they are same or different. The function accepts two strings as parameters and returns an integer whose value is
i)    less than 0, if the first string is less than the second
ii)    equal to 0 if both are same
iii) greater than 0, if the first string is greater than second

Example :

#include <stdio.h>

int main ()
{
  char name[] = "webtrickshome";
  char type[] = "tutorials";

  int difference = strcmp(name,type);

  printf("%d\n",difference);
}

5. strrev()

This function is used to reverse the given string except the null character.

Example :

#include <stdio.h>

int main ()
{
  char name[] = "webtrickshome";
  char type[] = "tutorials";

  printf("%s\n",strrev(name));
}

6. strlwr()

This function is used to convert all the string characters from uppercase to the lower case.

Example :

#include <stdio.h>

int main ()
{
  char name[] = "Webtrickshome";
  char type[] = "tutorials";

  printf("%s\n",strlwr(name));
}

7. strupr()

This function converts all the characters in the given string from lower case to upper case.

Example :

#include <stdio.h>

int main ()
{
  char name[] = "webtrickshome";
  char type[] = "tutorials";

  printf("%s\n",strupr(name));
}

Pointer

A pointer is special type of variable that contains a memory address of a value instead of the values itself. A pointer variable is declared with a specific data type, like any other normal variable, so that it will work only with memory address of a given type. Each pointer variable can point only specific type(int, char, float, double or any user defined data type). A pointer can have any name that is legal for other variable and it is declared in the same fashion like other variables but is always preceded by * operator.

Instating Pointers 

Address of a variable can be relegated to a pointer variable at the hour of announcement of the pointer variable. The instating a pointer with address variable is known as pointer introduction.

Example :

int num; 
int *a = &num;

When a pointer variable is first proclaimed, it doesn't have a legitimate location. The pointer is in this way instated as terrible pointer. 

A void pointer is an exceptional sort of pointer which can highlight factors of any information. 

Null Pointer

A NULL pointer is an uncommon pointer that stores nothing in memory address. We can characterize invalid pointer utilizing predefined steady NULL. 

int *ptr = NULL 

Pointer to Pointer

C permits the utilization of pointer that points to another pointer and share the memory address of a value. 

Example :

int a=20; 
int *p; 
int **q ( pointer to "a pointer to a number") 
p=&a; 
q=&p; 

Here, a will be an ordinary variable, p is  a pointer variable and q is twofold pointer variable. The location of pointer p has been doled out to twofold pointer (for example q focuses to another pointer p) and address of variable has been doled out to pointer p. In this manner, *p speaks to estimation of memory address pointed by p. Essentially, *q speaks to estimation of memory address pointed by q(i.e. memory address of a) and **q speaks to an incentive at the memory address pointed by *q that means estimation of a. 

Array of Pointers 

The different pointers of same sort can be spoken to by a cluster. Every component of such cluster speaks to pointer and they can highlight various areas. A variety of pointers can be proclaimed as:

data_type *pointer name[size]; 

Connection Between One Dimensional Array And Pointer

An array name is a pointer which speaks to the base location of cluster. In one dimensional array, address of first cluster component can be communicated as either &a[0] or basic as a. The location of the second cluster component can be composed as either &a[1] or as a+1, etc. The location of the exhibit component a+1 can be communicated as either &a[i] or as a+1. In the articulation a+1; a speaks to a+i, a speaks to cluster name (address of first component) whose components might be whole numbers, characters and so forth and [i] speaks to number amount. Along these lines, here a+i indicates a location that is a sure number of memory cells past the location of the principal array component. In this way, a[i] and *(a+ i) both speak to the element in that address. 

Example :

#include <stdio.h>
 
const int MAX = 3;
 
int main () {

   int  var[] = {10, 100, 200};
   int i, *ptr[MAX];
 
   for ( i = 0; i < MAX; i++) {
      ptr[i] = &var[i]; /* assign the address of integer. */
   }
   
   for ( i = 0; i < MAX; i++) {
      printf("Value of var[%d] = %d\n", i, *ptr[i] );
   }
   
   return 0;
}

Pointers and Multidimensional Array

The multi dimensional array can be spoken to with an equal pointer documentation like in single dimensional array. A multidimensional array is really an assortment of one dimensional array of lines. It is put away in memory in the column structure. Multidimensional array can be presented utilizing pointer as shown below.

Example :

#include <stdio.h>

int main () {

  int  arr[3][3] = {
    {1, 10, 100},
    {5, 4, 3},
    {6, 8, 0}
  };

  for(int i=0; i<3; i++) {
      for(int j=0; j<3; j++) {
         printf("arr[%d][%d]  Address: %p  Value: %d\n",i, j, &arr[i][j], arr[i][j]);
      }
   }

  return 0;
}

Passing Pointer To Function

A pointer can be passed to a function as a contention. Passing a pointer implies passing location of a variable rather than estimation of the variable. As address is passed for the situation, it is known as call by address or call by reference. When a pointer is passed to a function while calling, the proper contention of the function must be good with the provided pointer in the real contention. If the address of a variable is changed inside a function, the estimation of real factor is additionally changed. 

Example :

#include <stdio.h>

void getSeconds(unsigned long *par);

int main () {

   unsigned long sec;
   getSeconds( &sec );

   printf("Number of seconds: %ld\n", sec );
   return 0;
}

void getSeconds(unsigned long *par) {
   /* get the current number of seconds */
   *par = time( NULL );
   return;
}

String and Pointer

In C programming, a string is a sequence of characters which we save in an array. And in C programming language the \0 null character marks the end of a string. The array name itself is a pointer which focuses to first element of the array. 

Example :

#include <stdio.h>

int main() {

  char str[13] = "webtrickshome";

  char *ptr = str;

  while(*ptr != '\0') {
    printf("%c \n", *ptr);
    ptr++;
  }

  return 0;
}

0 Like 0 Dislike 0 Comment Share

Leave a comment