I am trying to execute following C program using gcc compiler.
#include <stdio.h>
int main()
{
int *a[] = {1,2,3,4,5,6};
printf("\narr0=%d\n", *a);
printf("arr1=%d\n", *(a+1));
printf("arr2=%d\n", *a+2);
printf("arr3=%d\n", *a+3);
printf("arr4=%d\n", *a+4);
return 0;
}
Output:-
arr0=1
arr1=2
arr2=9
arr3=13
arr4=17
I am not able to understand what is happening when I skip parenthesis for *a+2, *a+3, *a+4.
For *a+2 it manipulates as :
= *a+2
= *a+(4*2) 4 ->Size of int
= 1+(8)
So, *a+2 = 9
Same way it does for others.
But I am expecting output as following. (?)
arr0=1
arr1=2
arr2=3
arr3=4
arr4=5
I know, the way I have declared array of pointers in not good way to do it.
Can anyone explain what is happening here ?
You are declaring a bunch of pointers to invalid addresses, since the small integers are very typically not valid integer pointers. You should be getting compiler warnings for this by the way; it’s a good idea to read those and fix them before posting a question here. Or at least mention that you do get warnings.
As soon as you dereference any of these, undefined behavior strikes.
It’s good that you never do, all you do is index into the array itself, and print the pointers using the wrong format specifier (you should use
%p, not%d).