padawanTony
padawanTony

Reputation: 1359

Value of Pointer in C

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?

Upvotes: 10

Views: 6857

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

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.

Upvotes: 11

Lundin
Lundin

Reputation: 215115

1). You should print the address as printf("c address = %p\n", &c);. Now you attempt to print the address where the pointer variable itself is stored, which probably doesn't make much sense.

That being said, it might still be a valid address, assuming 64 bit addresses.

2). You will have to safely convert it to an integer which is guaranteed to be large enough to contain a pointer address:

#include <inttypes.h>

printf("c address = %" PRIuPTR "\n", (uintptr_t)&c);

Upvotes: 3

Related Questions