Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are &p and &a[0] different?

#include <stdio.h>

int main(void) {
    int a[4][2] = { {11, 12}, {21, 22}, {31, 32}, {41, 42} };
    int *p = a[0];

    printf("%d\n", *p);

    printf("%d\n", p); 

    printf("%d\n", a[0]);

    printf("%d\n", &p);

    printf("%d\n", &a[0]);

    printf("%d\n", a); 

    return 0;
}

Look at the above code.

In my understanding, since p equals a[0], &p and &a[0] are supposed to have the same value.

But the actual output looks like this:

11
1772204208
1772204208
1772204200
1772204208
1772204208

Why are &p and &a[0] different?

What does &p represent?

like image 547
Sleeping On a Giant's Shoulder Avatar asked Oct 02 '18 11:10

Sleeping On a Giant's Shoulder


2 Answers

&p yields the address of the pointer p which obviously has to be different from the adress of a[0].

like image 143
Swordfish Avatar answered Oct 24 '22 03:10

Swordfish


p Is a pointer to an integer. It is stored in an address and it also stores an address.

Printing p will print the address p points to.

Printing *p prints the value p points to.

Printing &p prints the address of p, which is unique to p and was allocated in the moment it was declared.

int *p_2 = &p;

p_2 will have the same value as &p

Every variable has its own unique address!

like image 34
sagi Avatar answered Oct 24 '22 03:10

sagi