I have the following code:
#include<stdio.h>
int main()
{
int(* a)[10]; //declare a as pointer to array 10 of int
int b[10]; // taken a array of 10 int
b[2]=32;
a=&b;
printf("b is on %p\n",&b);
printf("a is on %p\n",a);
printf("magic is %d\n",a[2]); // why this is not showing 32
return 0;
}
output:
b is on 0xbfa966d4
a is on 0xbfa966d4
magic is -1079417052
Here I have taken a
as pointer to array 10 of int which points to the array b
, so now why am I unable to get the value of 32 on a[2]
?
a[2]
is evaluated as *(a+2)
so now a has address of array b
so *(b+2)
and *(a+2)
are similar so why am I not getting value 32 here?
Edit : i got answer by using
(*a)[2]
but i am not getting how it works ... see when
a[2]
is *(a+2)
and a+2
is a plus 2 * sizeof(int[10])
bytes.
this way (*a)[2]
how expand?
Since a
is already a pointer, you have to dereference it in order to refer to the array that it points to:
(*a)[2]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With