2

Let us consider the following two programs in C language

Program #1

#include<stdio.h>

int main ()
{
    int x = 5;
    int *px;

    px = &x;

    printf ("&x = %p\n", &x);
    printf ("px = %p\n", px);
    return 0;
}

Program #2

#include<stdio.h>

int main()
{
    int x = 5;
    int *px = NULL;

    px = &x;

    printf("&x  = %p\n", (void *)&x);
    printf("px  = %p\n", (void *)px);
    return 0;
}

After compiling, I am getting no errors for both programs. But after compiling the #1, I am getting the following warning

format ‘%p’ expects argument of type ‘void *’, but argument 2 has type ‘int *’

After searching over stack exchange, I got that (void *) is a generic pointer, but my doubt is that, I declared px as a pointer variable to int, then why I need to cast to generic pointer instead of (int *). Why not %p can handle without type casting to (void *)?

Does it needed to cast to generic pointer whenever I print an address or pointer in-order to get zero warnings?

hanugm
  • 1,127
  • 3
  • 13
  • 44
  • 1
    What `type` does `man printf` tell you the `%p` ***format specifier*** expects? (hint: *"The `void *` pointer argument is printed in hexadecimal (as if by %#x or %#lx)"*) *Always* check the *man page* for prototype and type information. (they are actually quite good once you make friends with them, and when you do, you will never be Confused again `:)` – David C. Rankin Aug 13 '17 at 05:01
  • 2
    There are systems (albeit out-dated and convoluted) which use pointers of different sizes in the same executable. The standard guarantees that all pointers can be converted to a `void *`, and a `void *` has a known size, so `printf` uses `void *`. – user3386109 Aug 13 '17 at 05:06

0 Answers0