satyres
satyres

Reputation: 377

Pointer in C++ Same variable have two different address

Normally with this code we should get the same address of the pointer : if we have such a code normally , i and &i point to the same address

int *i=NULL;
int k=5;
i=&k;
printf("%p %p",&i,i);

here is the result of printf (only the last digit is different): 0x7fff5fbff8b8 0x7fff5fbff8b4

can any one please explain me why ?

Upvotes: 1

Views: 1611

Answers (2)

BigTailWolf
BigTailWolf

Reputation: 1028

i is a pointer points to an integer. i's value is an address(the address of k).

&i is i's address.

You just output two different addresses.

You can do this:

#include <cstdio>

int main()
{
   int *i=NULL;
   int k=5;
   i=&k;
   int** j = &i;
   printf("%p %p %p",&i,i,j);
}

You can get the output:

[wolf@Targaryen]:~$ r
0xbfc8a1a8 0xbfc8a1a4 0xbfc8a1a8

See the first address is the same as the third. Because j's value is i's address.

Upvotes: 3

Yu Hao
Yu Hao

Reputation: 122383

Because they are not the same. i is a pointer which contains the address of the variable k, &i is a pointer which contains the address of the variable i.

Upvotes: 11

Related Questions