Pointer value in C

I started learning C (so, you know .. pointers).

I have this code:

#include <stdio.h> #include <string.h> int main (int argc, char* argv[]) { char c = 'c'; char* cptr = &c; printf("c = %c\n", c); printf("*cptr = %c\n", *cptr); printf("c address = %p\n", &c); } 

My conclusion:

 c = c *cptr = c c address = 0x7fff0217096f 

When I convert a hexadecimal digit to decimal, I get: 140720994002157

My questions:

1) Does this decimal value indicate a memory address? Isn't that too big?

2) How can I print the value of a pointer (which means the address of the variable c ) as a decimal?

+8
c pointers memory-address
source share
2 answers

Is it too [address]?

This is a virtual address, meaning that its numeric value is not necessarily a sequential number of bytes in physical memory. Moreover, different processes can store different data on the same virtual address, since each of them has its own individual address space.

How can I print the value of a pointer in integer format?

Use uintptr_t to represent the pointer as an integer value, then print it using the PRIuPTR macro:

 #include <stdio.h> #include <inttypes.h> int main(void) { char c = 'x'; char *p = &c; uintptr_t x = (uintptr_t)p; printf("Pointer as decimal: %"PRIuPTR"\n", x); return 0; } 

Demo version

+7
source share

one). You must print the address as printf("c address = %p\n", &c); . Now you are trying to print the address in which the pointer variable itself is stored, which probably does not make much sense.

However, it can still be a valid address, assuming 64-bit addresses.

2). You will need to safely convert it to an integer that is guaranteed to be large enough to contain the address of the pointer:

 #include <inttypes.h> printf("c address = %" PRIuPTR "\n", (uintptr_t)&c); 
+2
source share

All Articles