How to use "pointer to array 10 of int"?
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; }
exit:
b is on 0xbfa966d4 a is on 0xbfa966d4 magic is -1079417052
Here I took a
as a pointer to array 10 of int , which points to array b
, so now why can't I get the value 32 on a[2]
?
a[2]
evaluates to *(a+2)
, so it now has the address of array b
, so *(b+2)
and *(a+2)
are similar, so why don't I get the value 32 here?
Edit: I got a response using
(*a)[2]
but I donβt understand how it works ... see when
a[2]
- *(a+2)
, and a+2
is plus 2 * sizeof(int[10])
bytes.
so (*a)[2]
how to deploy?
#include<stdio.h> int main() { int(* a)[10]; //declare a as pointer to array 10 of int int b[10]; // taken a arry 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 %p\n",a + 2); // Changed to show pointer arithmetic return 0; }
The following is printed:
b is on 0xbfe67114 a is on 0xbfe67114 magic is 0xbfe67164
Do you see what is happening? magic
minus a
equals 80
, that is 4 * 10 * 2. This is due to the fact that a
is a pointer to an array of ten integers, so sizeof(*a) == 10 * sizeof(int)
, not sizeof(a) == sizeof(int)
, what did you expect. Pay attention to the types in pointer arithmetic next time!
I was not able to add a comment since it requires 50 rep. Therefore, here comes my question about the question posed. Sorry if I break some rules by posting a question in the answer box. This question shows that we must be careful when doing pointer arithmetic. But what is the good use of pointers to an array if the same thing can be done simply by using pointers to integers ....?