指针在 printf() 中不起作用
打印指针时出现问题。每次我尝试编译下面的程序时,都会出现以下错误:
pointers.c:11: warning: format ‘%p’ expects type ‘void *’, but argument 2 has type ‘int *’
我显然在这里缺少一些简单的东西,但从我见过的类似代码的其他示例来看,这应该可以工作。
这是代码,任何帮助都会很棒!
#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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
只需将 int 指针转换为 void 即可:
您的代码是安全的,但您正在使用
-Wformat
警告标志进行编译,该标志将检查对printf()
的调用和scanf()。Simply cast your int pointer to a void one:
Your code is safe, but you are compiling with the
-Wformat
warning flag, that will type check the calls toprintf()
andscanf()
.请注意,您会收到一个简单的警告。您的代码可能将按预期执行。
printf 的
"%p"
转换说明符需要一个void*
参数;pt1
的类型为int*
。这个警告是好的,因为
int*
和void*
在奇怪的实现中可能具有不同的大小或位模式或其他内容。通过强制转换将
int*
转换为void*
...... 一切都会好的,即使是在奇怪的实现上。
Note that you get a simple warning. Your code will probably execute as expected.
The
"%p"
conversion specifier to printf expects avoid*
argument;pt1
is of typeint*
.The warning is good because
int*
andvoid*
may, on strange implementations, have different sizes or bit patterns or something.Convert the
int*
to avoid*
with a cast ...... 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:
该消息说明了一切,但这只是一个警告,而不是错误本身:
The message says it all, but it's just a warning not an error per se:
这对我来说效果很好:
你不需要将它转换成任何东西,除非你想......
This worked just fine for me:
You don't need to cast it as anything, unless you wanted to...