Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why the address of the pointer and pointer value are different at C

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  • &x produces the address of x.
  • &ptr produces the address of ptr.
  • ptr produces the address stored in ptr, i.e. the address of x.

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading