Advertisements
i create ptr pointer and set it to adress of x then print both of the adress why they are different each other ?
#include <stdio.h>
int main()
{
int *ptr;
int x = 20;
ptr = &x;
printf("adress of x = %p\n", &x);
printf("adress ptr = %p\n", &ptr);
}
Output :
adress of x = 0x7ffe31da2274
adress of ptr = 0x7ffe31da2278
>Solution :
&x
produces the address ofx
.&ptr
produces the address ofptr
.ptr
produces the address stored inptr
, i.e. the address ofx
.
The addresses of x
and ptr
are obviously going to be different, since different values are stored in each (the number 20
in x
, and the address of x
in ptr
), as illustrated by the following memory layout:
int x int* ptr
@ 0x1008 @ 0x1000 <-- Some made up addresses
+-----------+ +-----------+
| 20 | | 0x1008 |
+-----------+ +-----------+
If you want the value stored in ptr
(the address of x
), simply use ptr
.
printf( "address of x = %p\n", (void*)&x ); // 0x1008
printf( "address of ptr = %p\n", (void*)&ptr ); // 0x1000
printf( "address in ptr = %p\n", (void*)ptr ); // 0x1008