cpointersprintfvoid-pointerssize-t

Expression evaluation in printf with %p


I am studying pointers in C. Trying a bunch of things to make sure I understand how pointers work, I found something that I don't understand. Here's the snippet of the code in question:

int b = 30;
printf("(void *)(size_t)b: %p\n", (void *)(size_t)b);

Output:

(void *)(size_t)b: 0x1e

That is the value 30, stored at "b", in hexadecimal. I have put the expression inside so I know which one is which in the console.

I am compiling the code with GCC 13.2.1-6 and the flags -Wall -Werror -Wextra -std=c17 -pedantic-errors in a x86-64 Linux machine. I don't know if it's relevant (I'm a beginner) but an int has 4 bytes for me.

The code compiles fine with no errors. I couldn't understand why it gives that output.


Solution

  • int b = 30;
    

    You now have an int value of 30 (0x1e).

    (size_t)b
    

    You tell the compiler to treat this as a size_t value of 30 (0x1e).

    (void *)(size_t)b
    

    You tell the compiler to treat this size_t value of 30 (0x1e) as a void *.

    printf("%p", (void *)(size_t)b);
    

    You print the value of the pointer, which is 30 (0x1e). Note that %p prints the pointer, not what the pointer points to.

    And you mustn't dereference that pointer (by adding an asterisk in front of (void *)(size_t)b), because your pointer isn't valid, i.e. it does not actually point to something, so dereferencing it would be undefined behavior (i.e., bad).

    If you want to print the address of b, you need to take that address, using the address operator &:

    int b = 30;
    printf("%p", (void *)&b);