1

I was manipulating some pointers in a c code and I found something that I couldn't understand.

int main(){
   int tab[]={4,6,8,9,20};
   printf("%p %p",tab,&tab);
   return 0;
}

I've tried to print the variable tab and its address knowing that tab holds the address of the first element in the array and the address of tab itself would be a random address value but for whatever reason the program output the same value and I found this really odd so ill be grateful if someone could explain the reason to me.

GG33
  • 31
  • 3

2 Answers2

5

If we draw out the array and the common pointers to it, it would look something like this:

+--------+--------+--------+--------+--------+
| tab[0] | tab[1] | tab[2] | tab[3] | tab[4] |
+--------+--------+--------+--------+--------+
^
|
&tab
|
&tab[0]

Both the pointers, &tab, and &tab[0] (which is what plain tab decay to) points to the same location.

The type are different though: &tab is a pointer to the array and will have the type int (*)[5], while &tab[0] is a pointer to a single int element and therefore have the type int *.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

When you declare array like

int tab[]={4,6,8,9,20};

Compiler reserved the memory for array tab of 5 array element. it will be decay to an expression of type "pointer to int” and the value of expression will be the first address of the first element of array tab. That’s why tab array store the base address that is &tab[0]

This is the reason you have same out put for both tab and tab[0].

in other words,

printf("%p",tab);

equivalent to

printf("%p",&tab[0]);
user23
  • 41
  • 7