C Pointers and Arrays

In this chapter we will learn relation between array and pointers as well as their diffrences.

When an array is declared, compiler allocates sufficient amount of memory to contain all the elements of the array and array name refers the base address of that array, or we can say array name store address of first element of array.

Let’s take an example and assume base address of following array is 5000:-

int arr[5] = {10, 20, 30, 40, 50};

Here array name ‘arr’ give the base address, which is constant pointer pointing to element arr[0].  arr containing same address as arr[0] that is 5000. Hence arr is equal to &arr[0]

We can not apply increment or decrement operator to base address of an array like:

arr++  or ++arr     /* This will give compile time error, we can not change the base address of an array*/

Array element             arr[0]   arr[1]   arr[2]   arr[3]   arr[4]

Address of element     5000    5004    5008    5012    5016

Pointer to an array

Just take one C program to demonstrate things clear, we will learn how pointer is used to access an array:

int main()

{

/* assuming base address of array is 5000 */

int i, arr[5] = {10, 20, 30, 40, 50};

printf(“arr = %u\t &arr[0] = %u\n”,arr, &arr[0]);

int *ptr , *ptr1;

ptr = arr;   /* Now pointer variable ptr is pointing to an array */

ptr1 = &arr[0];  /* Now pointer variable ptr is pointing to an array */

/* Here we can access every element of array using increment operator on pointer variable ptr and ptr1 */

for (i=0; i<5; i++)

{

 printf(“ptr = %d/t ptr1 = %d\n”,*ptr,*ptr1);

 ptr++;

 ptr1++;

}

}

Output: In O/P we can see both ptr and ptr1 having same value because they were assigned to same address, means arr is equivalent to &arr[0].

arr = 5000       &arr[0] = 5000

ptr =    10        ptr1 = 10

ptr =    20        ptr1 = 20

ptr =    30        ptr1 = 30

ptr =    40        ptr1 = 40

ptr =    50        ptr1 = 50

Important points to note:

arr[i] is equivalent to i[arr]

arr+i is equivalent to &arr[i]

*(arr+i) is equivalent to arr[i]

*arr == *(arr+0) == arr[0]

Array of pointers

Also we can have an array of pointers, where each element of array is a pointer itself. It is helpful to store a list of strings, see an example below:

int main ()

{

char *str[3] = {  “Welcome”, “to”, “gyantoday”,};

int i = 0;

for ( i = 0; i < 3; i++)

{

printf(“str[%d] = %s\n”, i, str[i] );

}

return 0;

}

Output:

str[0] = Welcome

str[1] = to

str[2] = gyantoday

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.