I have 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 output is:
c = c
*cptr = c
c address = 0x7fff0217096f
When I convert the hexadecimal above to decimal, I get: 140720994002157
My questions:
1) Does this decimal value represent the memory address? Isn't it too big?
2) How can I print the value of the pointer (which means the address of the c
variable) as a decimal?
Put another way, the pointer does not hold a value in the traditional sense; instead, it holds the address of another variable. A pointer "points to" that other variable by holding a copy of its address. Because a pointer holds an address rather than a value, it has two parts. The pointer itself holds the address.
A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable address.
To get the value pointed to by a pointer, you need to use the dereferencing operator * (e.g., if pNumber is a int pointer, *pNumber returns the value pointed to by pNumber . It is called dereferencing or indirection).
The pointer is 8 bytes, because you are compiling for a 64bit system. The int it is pointing at is 4 bytes.
Isn't [the address] too big?
This is a virtual address, meaning that its numerical value does not necessarily represent the sequential number of the byte in physical memory. Moreover, different processes may keep different data at the same virtual address, because each one has its individual address space.
How can I print the value of the pointer in an integer format?
Use uintptr_t
to represent the pointer as an integer value, then print using 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With