Pointer will not work in printf()
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;
}
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()
.
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.
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);
The message says it all, but it's just a warning not an error per se:
printf("Address of p1: %p\n", (void*)pt1);
This worked just fine for me:
printf("Pointer address: %p.", pxy);
You don't need to cast it as anything, unless you wanted to...
精彩评论