35

Having an issue with printing a pointer out. Every time I try and compile the program below i get the following error:

pointers.c:11: warning: format ‘%p’ expects type ‘void *’, but argument 2 has type ‘int *’

I'm obviously missing something simple here, but from other examles of similar code that I have seen, this should be working.

Here's the code, any help would be great!

#include <stdio.h>

    int main(void)
    {
       int x = 99;
       int *pt1;

       pt1 = &x;

       printf("Value at p1: %d\n", *pt1);
       printf("Address of p1: %p\n", pt1);

       return 0;
    }
2
  • 2
    The warning description seems just fine to me. Cast it to void before sending it to printf. instead of pt1, (void*)pt1
    – Milan
    Mar 24, 2011 at 10:51
  • Try adding an ampersand to pt1 and see if that works.
    – Nocturnal
    Mar 24, 2011 at 10:51

5 Answers 5

52

Simply cast your int pointer to a void one:

printf( "Address of p1: %p\n", ( void * )pt1 );

Your code is safe, but you are compiling with the -Wformat warning flag, that will type check the calls to printf() and scanf().

2
10

Note that you get a simple warning. Your code will probably execute as expected.

The "%p" conversion specifier to printf expects a void* argument; pt1 is of type int*.

The warning is good because int* and void* may, on strange implementations, have different sizes or bit patterns or something.

Convert the int* to a void* with a cast ...

printf("%p\n", (void*)pt1);

... and all will be good, even on strange implementations.

2
  • 1
    Even if they have the same size, they may be conveyed to the called function differently under a strange calling convention.
    – caf
    Mar 24, 2011 at 12:11
  • Thanks @caf, answer reviewed to cover ALL cases :)
    – pmg
    Mar 24, 2011 at 12:35
2

In this case, the compiler is just a bit overeager with the warnings. Your code is perfectly safe, you can optionally remove the warning with:

printf("Address of p1: %p\n", (void *) pt1);
1

The message says it all, but it's just a warning not an error per se:

printf("Address of p1: %p\n", (void*)pt1);
0

This worked just fine for me:

printf("Pointer address: %p.", pxy);

You don't need to cast it as anything, unless you wanted to...

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.