Pointer to array and Array of Pointers | C Programming and Computer Geeks

Search MY Blog

Tuesday 15 April 2014

Pointer to array and Array of Pointers



Pointers and Arrays
Pointers and Arrays
What Is the difference between the following three declarations?

int *ptr1[5];
int  (*ptr2)[5];
int* (ptr3[5]);



Answer:
int *ptr1[5];
   Here in int *ptr1[5], ptr1 is an array of 5 integer pointers (An array of int pointers).

int  (*ptr2)[5];
   And in int (*ptr2)[5], ptr2 is a pointer to an array of 5 integers (A pointer to an array of integers).

int* (ptr3[5]);
   This is same as ptr1 (An array of int pointers).


What will be the Output of the below program?

void main(void)
{
     int arr1[4] = {1, 3, 5, 7};
     int arr2[4] = {2, 4, 6, 8};

     int (*ptr[2])[4] = {arr1, &arr2};
    
     printf("%d, %d", (*ptr[1])[2], *(**(ptr) + 3));

}

Try to explain (*ptr[1])[2] And *(**(ptr) + 3) expressions and outputs by step by step..
Learning Points: Pointers to array/Array of pointers and resolving pointer expressions.

Program Explanation:
int (*ptr[2])[4] = {arr1, &arr2};
Here ptr is a array of 2 pointers,In which each pointing to an array of 4 integers.
from the above C statement this ptr is assigned as {arr1,&arr2}.
Here arr1 is a base address to array arr1 also called pointer to the first element of array.
And &arr2 is an address of array(arr2) also called entire array address).
ptr array elements(ptr[0],ptr[1]) expects the address of type int(*)[4]. But ptr[0] is assigned arr1,which is of type int*.
So this is the flaw in code. This may not lead to any compilation error, but it gives warning.
Even though you have given base address(arr1) to ptr[0], it will considers it as pointer to an array of 4 int (array address or entire array address).

printf("%d, %d", (*ptr[1])[2], *(**(ptr) + 3));
From the above C Statement

( *ptr[1] )[2]:
( *ptr[1] )[2] ==> (* ( ptr[1] ) ) [2]  ==> (* ( &arr2 ) ) [2] ==> ( arr2 ) [2] ==> arr2[2] ==> which equals the value 6

*(**(ptr) + 3):
**(ptr) ==> *(*ptr) ==> *(&arr1) ==>arr1(base address) 
Now

*(**(ptr) + 3) ==> *( arr1 + 3) ==> Nothing but arr1[3] ==> which equal to the value 7

Output:
6, 7

Please Correct me if anything is wrong. Please share your inputs and suggestions in comments.
Find more on C Pointer Concepts Here


1 comment:

  1. Best ever explanation on Pointers...
    This one post alone on Pointers cleared all my doubts..
    Thanks for sharing this post.

    ReplyDelete

Search This Blog