Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange Behavior of Pointer of an array in C

Tags:

arrays

c

pointers

Here is a code which I wrote to test/understand the behavior of pointers of/in an array

int main(void){
    int a[4];
    memset(a, 0, sizeof(a));
    printf("%x %x\n",a,&a);
}
Output of the above program on my machine:
bfeed3e8 bfeed3e8

I can't understand why are the values a and &a is same. From what I understand &a is supposed to give the address of memory location where a is stored. What is the explanation for this kind of behavior?

like image 866
gibraltar Avatar asked Dec 09 '22 00:12

gibraltar


2 Answers

&a does give you the address of a. a gives you a, which, because it's an array, decays to a pointer to a.

Or to be pedantic, it decays to a pointer to a[0].

like image 154
Mr Lister Avatar answered Dec 14 '22 22:12

Mr Lister


In that context, the array name a decays into a pointer to its first element. Did you mean

printf("%x %x\n",a[0],&a);
like image 25
Daniel Fischer Avatar answered Dec 14 '22 23:12

Daniel Fischer