-3
#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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
claw107
  • 71
  • 1
  • 9
  • 5
    `printf("%d\n",ptr);` is undefined behavior. – Ari0nhh Dec 20 '16 at 05:47
  • 6
    the size of pointer is not always the same as size of int – phuclv Dec 20 '16 at 05:47
  • 1
    Also, use `%zu` for `size_t` (instead of `%u`), and `%zd` for `ssize_t`. – e0k Dec 20 '16 at 05:48
  • 1
    See [Correct format specifier to print pointer (address)?](http://stackoverflow.com/questions/9053658/correct-format-specifier-to-print-pointer-address) – e0k Dec 20 '16 at 05:52
  • `a` is not supposed to be printed out by `%p` – phuclv Dec 20 '16 at 05:58
  • Note that 0x7FFE120232C40 bears little resemblance to 302197824 (though the hex representation of the decimal is 0x12032C40, which shows that you've got a data truncation problem); the magnitudes of the values are not commensurate, though you're nominally printing the same value. That alone demonstrates that there are problems with your code (and that you're compiling for 64-bit CPUs, and that it is a little-endian CPU — aka Intel x86_64 or compatible). – Jonathan Leffler Dec 20 '16 at 06:02

4 Answers4

1

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)

e.jahandar
  • 1,715
  • 12
  • 30
0

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.

599644
  • 561
  • 2
  • 15
0

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);
Bishal
  • 807
  • 1
  • 5
  • 20
0

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).

sjsam
  • 21,411
  • 5
  • 55
  • 102