I was experimenting with array of pointers address calculation arithmetic.I got confused with the output of the above code.Could anyone explain whats happening?
void foo()
{
int i=10,k=3,l=20,m=30;
int *ary[2];
ary[0]=&i;
int b=20;
ary[1]=&k;
printf("%d\n",ary[0][1]);
}
Output is 3
Second program
void foo()
{
int i=10,k=3,l=20,m=30;
int *ary[2];
ary[0]=&i;
int b=20;
ary[1]=&b;
printf("%d\n",ary[0][1]);
}
Output is 20.
How is address calculation done in these above codes?
In both code samples
ary[0]is a pointer to a single integer. So when you doarray[0][1]you’re accessing that pointer out of bounds. So the behavior of both of your code samples is undefined.The reason that you’re getting the behavior you’re seeing on your particular compiler is probably, that all the variables whose address you don’t take are stored in registers and not in memory (or possibly they aren’t stored at all because you never use them).
So in example 1 the only variables in memory are i and k. And in example 2 the only variables in memory are i and b. So in example 1
kis the variables that comes directly afteriin memory and example 2 that variable isb.