I have some code (below) where I am assigning the address of an integer array to a pointer. I am assigning in two ways and expect two different outputs but in both cases the output is the same.
main()
{
int a[]={11,2,3};
int *p=&a;
printf("%d",*(p+1));
}
It should give me some garbage value since p is pointing to next 1D array
main()
{
int a[]={11,2,3};
int *p=a;
printf("%d",*(p+1));
}
This should print 2.
However BOTH of these functions print 2.
This is not what I expected. Can anyone explain what’s happening?
Can anybody tell how i make pointer pointing to whole array than to just individual element.
If you compile the first program you will get a compiler warning:
Because the type of
pis pointer to integer but the type of&aispointer to array of integer. Compiling the second program is fine, because againphas typeint*andahas typeint[]` (i.e., array of integer) but in C, you can pass/assign an integer array to an integer pointer just fine. The value of the pointer is assigned the starting address of the array.When you define an array with square brackets in C, the array is placed immediately in the stack or data section, so the starting address of the array is the same as the address of the array variable itself! This is different from arrays created with
malloc.What this means for you is this: Suppose the variable
ais allocated at address 4e78ccba. This means that&ais 4e78ccba. But in C, the value ofawhen passed/assigned to a pointer is by definition the address of the beginning of the array, so this is also 4e78ccba.Again, if you set things up with malloc things will be different. (Try it!!) And by the way, pay attention to the warnings. 🙂 This is an interesting question because C is so weakly typed it only gave you a warning in the first case. A stronly typed language would not have liked the mixing of an integer pointer with an integer array pointer.
ADDENDUM
Here is some code that shows how you can actually differentiate the pointer to the first element and the pointer to the whole array:
This program outputs