Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What int (*ptr)[4] really means and how is it different than *ptr?

int (*p)[4] , *ptr;
int a[4] = {10,20,30,40};
printf("%p\n%p\n%p",&a,a,&a[0]);
p = &a ;
//p=a;        gives error

//ptr = &a;   gives error
 ptr = a;

Output:

0x7ffd69f14710
0x7ffd69f14710
0x7ffd69f14710

I tried to understand what a, &a, and &a[0] returns and its the memory address of starting variable. So, why am I getting errors in some of these assignments ?

I mean, if p = &a = 0x7ff... works, why not p = a = 0x7ff.. ?

If possible, can anyone please make me understand through a block diagram of where this p and ptr is actually pointing to too. Or are they just pointing same. But they're different things that for sure I know.

like image 389
SpawN Avatar asked Jan 26 '23 00:01

SpawN


1 Answers

Imagine pointers are laser pointers, with different colors (red for pointers to int, green for pointers to arrays, ...) and variables are things you can point to with the correct laser pointer, ie, you cannot use a green laser pointer to point to a char variable.

Ok, so you have int a[4] an array (of 4 ints). Use a green pointer to point to it: int (*green)[4] = &a;... you also have an int (a[0]) which you can point to with a red pointer: int *red = &a[0]; /* in most contexts 'a' by itself is converted to "address of first element": &a[0] is the same as a */.

Now ask your color-blind friend where the pointers point to :)
As far as your friend is concerned, they are equal and point to the same "place"... but you tricked your friend! Compilers are color-blind and don't like being tricked.

like image 85
pmg Avatar answered Jan 29 '23 13:01

pmg