C语言 指针在 printf() 中不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5417967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pointer will not work in printf()
提问by Chris
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;
}
回答by Macmade
Simply cast your int pointer to a void one:
只需将您的 int 指针转换为空指针:
printf( "Address of p1: %p\n", ( void * )pt1 );
Your code is safe, but you are compiling with the -Wformatwarning flag, that will type check the calls to printf()and scanf().
您的代码是安全的,但您正在使用-Wformat警告标志进行编译,这将检查对printf()和的调用scanf()。
回答by pmg
Note that you get a simple warning. Your code will probablyexecute as expected.
请注意,您会收到一个简单的警告。您的代码可能会按预期执行。
The "%p"conversion specifier to printf expects a void*argument; pt1is of type int*.
"%p"printf的转换说明符需要一个void*参数;pt1是 类型int*。
The warning is good because int*and void*may, on strange implementations, have different sizes or bit patterns or something.
警告是好的,因为int*并且void*在奇怪的实现中可能具有不同的大小或位模式或其他东西。
Convert the int*to a void*with a cast ...
使用演员表将其转换int*为 a void*...
printf("%p\n", (void*)pt1);
... and all will be good, even on strange implementations.
... 一切都会好起来的,即使是在奇怪的实现上。
回答by Erik
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);
回答by karlphillip
The message says it all, but it's just a warning not an error per se:
该消息说明了一切,但这只是一个警告,而不是本身的错误:
printf("Address of p1: %p\n", (void*)pt1);
回答by ClaireBookworm
This worked just fine for me:
这对我来说很好用:
printf("Pointer address: %p.", pxy);
You don't need to cast it as anything, unless you wanted to...
你不需要把它作为任何东西,除非你想......

