What exactly is %p and why is it different from printing the int value of pointer by using %d?

518 views Asked by At
#include <stdio.h>

int main()
{
    int *ptr;
    int a=2;
    ptr=&a;
    printf("%p\n",ptr);
    printf("%d\n",ptr);
    printf("%p\n",a);
    return 0;
}

The output I get is:

% ./a.out
0x7ffe12032c40
302197824
0x2
%

The value of the first two output changes (obviously because of ASLR) and the 0x2 remains constant.

4

There are 4 answers

0
e.jahandar On BEST ANSWER

The size of pointer isn't equal size of int, So you can't use %d instead of %p, %p is used for printing value stored in pointer variable, also using %p with int variable is undefined behavior (if you're on system which pointer and int have same size you may see correct result, but as C standard its an undefined behavior )

sizeof int is defined by compiler, different compilers may have different size of int on single machine, but pointer size is defined by machine type (8,16,32,64 bit)

0
599644 On

It is for printing pointers. In the same way you don't print a float with %d you should not be printing a pointer with %d.

0
Bishal On

0x2 is simply the hex representation of integer 2. That is why you see that output

printf() prints the value of variable a in hex format. If you want to print the address of a, do the following

printf("%p",&a);
0
sjsam On

When you use %p as in

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

%p is the format specifier for pointers, you get the expected results

When you use %d as in

printf("%d\n",ptr);

%d is the format specifier for signed integers, you get unexpected results because the size of pointers (which is usually 8 bytes) can be different from size of signed integers(which is usually 4 bytes).