简体   繁体   中英

C Programming printing pointers

I have this bit of code:

printf("Address for ptr_one %p\n", &ptr_one);
printf("Non-Address for ptr_one %p\n", ptr_one);
printf("value for ptr_one %p\n\n", *ptr_one);

output:

Address for ptr_one 0xffffcbd8
Non-Address for ptr_one 0x600042b26
value for ptr_one 0x19

From what I understand the first line is the pointer address, and the third is the value which is at that address. But what is the second line printing out exactly?

It was initialized as such:

int *ptr_one = (int *)malloc(sizeof(int));
*ptr_one = 25;

edit: added initialize code

It looks like you have code along the lines of:

int one = 0x19;
int *ptr_one = &one;

(you've since edited your code to show the actual situation but it's functionally identical to what I've shown above (in terms of memory and pointers to memory anyway) so that I don't need to change it).

What you then have is:

(ptr_one "variable")
    |
    V
+---------------+     +-----------+
| ptr_one value | --> | one value |
+---------------+     +-----------+

with the following descriptions:

  • Address for ptr_one 0xffffcbd8 is the address of the actual ptr_one variable, where it's stored in memory.
  • Non-Address for ptr_one 0x600042b26 is the value of the ptr_one variable which is also the address of the one variable.
  • value for ptr_one 0x19 is the value of the one variable.

第一行是指针的内存地址,第二行是指针指向的地址,第三行是该地址的第一个值。

Your example is a bit terse and doesn't mention the type of ptr_one . Suppose you have

int x=10;
int *ptr_one=&x;

Then

printf("Address for ptr_one %p\n", &ptr_one);

prints the address of the pointer ie ptr_one

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

prints the address of x ( ptr_one is a pointer after all.)

printf("ptr_one points to %p\n\n", *ptr_one);

prints the value of x (Here you dereference the pointer to gets the value stored in it)

The ptr_one is an intiger pointer present in address location 0xffffcbd8 . Currently it points to an address 0x600042b26 . In address 0x600042b26 we have the value 25 in it.

This link shows how ptr_one is allocated in memory

Hope this provides the answer..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM