Home > database >  printf("%d", &a) output a random number 36767236871
printf("%d", &a) output a random number 36767236871

Time:03-07

What is difference between %d and %p when printing?

For example:

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

CodePudding user response:

The printf function supports different conversions for different types of arguments: %d produces a decimal representation (d for decimal) for an argument of type int, %p produces a system dependent representation of a void pointer (p for pointer)

There are multiple problems in your code:

  • you pass the address of an int variable, hence a type int * where printf expects an int for the %d conversion: This has undefined behavior
  • you pass the address of an int variable, hence a type int * where printf expects an void * for the %p conversion: This has undefined behavior
  • you did not include <stdio.h> and you call the function printf without a proper prototype: the prototype inferred from the call is incompatible with the actual definition, so the behavior is undefined.

The output you observe is the result of undefined behavior: it is unpredictable and potentially irreproducible: on my system, I get different output every time I run the program, even without recompiling. Undefined behavior means anything can happen.

Here is a modified version:

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

int main() {
    int a = 9;

    printf("%d\n", a);
    printf("%p\n", (void *)&a);

    printf("0x%"PRIxPTR"\n", (uintptr_t)&a);
    printf("%p\n", (void *)NULL);
    printf("0x%"PRIxPTR"\n", (uintptr_t)NULL);

    return 0;
}

Output:

9
0x7fff54823844
0x7fff54823844
0x0
0x0

The last conversion takes a uintptr_t, an integer type large enough to store an integer representation of a pointer. On my system, OS/X, the %p conversion produces the same output as 0x%x for the corresponding integer type.

CodePudding user response:

Will output something like:

-1807747332, 
00000083943ff6fc

The format specifier converts the value of the corresponding variable to the format data type. %d converted it to a signed integer. If you use %p it simply treats the value as the memory address of a pointer and prints it in hexadecimal.

  • Related