Home > Back-end >  Pointers and addresses in c
Pointers and addresses in c

Time:12-23

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.

CodePudding user response:

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 *.

CodePudding user response:

Because both are the same, :), tab is also the pointer, so it's basically &tab. Don't be confused, it's the way array pointer is defined

  • Related