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;
    }
Chris
  • 7,996
  • 11
  • 66
  • 98

5 Answers5

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

Macmade
  • 52,708
  • 13
  • 106
  • 123
  • Oh OK. I'm new to C and hadn't learned to distinguish between compiler message types until now. Thanks. – Chris Mar 24 '11 at 10:57
  • 1
    This behavior was determined as valid by gcc developers, see http://gcc.gnu.org/bugzilla/show_bug.cgi?id=26542 See also a detailed explanation by Jonathan Leffler: http://stackoverflow.com/questions/9053658/correct-format-specifier-to-print-pointer-address – Alex Cohn Sep 03 '12 at 09:06
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.

pmg
  • 106,608
  • 13
  • 126
  • 198
  • 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 '11 at 12:11
  • Thanks @caf, answer reviewed to cover **ALL** cases :) – pmg Mar 24 '11 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);
Erik
  • 88,732
  • 13
  • 198
  • 189
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);
karlphillip
  • 92,053
  • 36
  • 243
  • 426
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...

ClaireBookworm
  • 101
  • 1
  • 9