当我尝试编译此代码时:
void main()
{
float x;
x=6.5;
printf("Value of x is %f, address of x %ld\n", x, &x);
}
它给了我这个错误:
pruebaso. c:在函数'main'中:
pruebaso.c:5:9:警告:内置函数“printf”的隐式声明不兼容 [默认启用]
printf(" x的值是%f,x的地址是%ld\n ",x,
^
pruebaso. c: 5:9:警告:格式'%ld'需要类型为'long int'的参数,但参数3的类型为'浮点数*'[-Wformat=]
我在另一个论坛上看到,解决办法是先对一个空指针进行强制转换:http://www.linuxquestions.org/questions/programming-9/beginning-c-programming-how-to-print-memory-locations-printf-conversion-number-927305/
但是做出这样的改变,
printf("Value of x is %f, address of x %ld\n", (double)x, (void *)&x);
现在给我一个警告:
pruebaso. c:在函数'main'中:
pruebaso.c:5:9:警告:内置函数“printf”的隐式声明不兼容 [默认启用]
printf(" x的值是%f,x的地址是%ld\n ",(double)x,(void *)
^
普鲁巴索。c: 5:9:警告:格式“%ld”需要“long int”类型的参数,但参数3的类型为“void*”[-Wformat=]
有人能告诉我怎么才能在没有得到警告的情况下解决这个问题吗?
非常感谢。
您需要包含<代码>
在C90中,使用< code>printf()而不使用< code >
#include <stdio.h>
int main(void)
{
float x = 6.5;
printf("Value of x is %f, address of x %p\n", x, (void *) &x);
}
< code>%p格式说明符用于打印指针。从技术上讲,它必须与< code>char *或< code>void *指针一起使用。在现代系统中,这不会影响结果;但是将其他指针类型传递给< code>%p在技术上会调用未定义的行为(这是不好的)。
您的代码中的< code>%ld格式是错误的,尽管它可以在大多数系统上工作。首先,它需要一个< code>long参数,这需要强制转换(即使这种转换只会对少数系统产生影响)。其次,即使添加了强制转换,也不能保证指针中的所有信息都保留下来(它可能会删除一些位或做其他事情)。实际上,64位Windows系统是唯一一个转换为< code>long位的系统,这种转换在其他任何地方都可以正常工作。
所以使用< code>%p并强制转换为< code>void *。
void main()
{
float x;
x=6.5;
printf("Value of x is %f, address of x %ld\n", x, &x);
}
眼前的问题是您缺少必需的#include
#include <stdio.h>
int main(void)
{
float x;
x = 6.5;
printf("Value of x is %f, address of x %p\n", x, (void*)&x);
}
为了解释我所做的更改:
#include
如果在定义函数之前使用它们,C会隐式声明函数,这会导致错误“内置函数'printf'的不兼容隐式声明”。若要解决此问题,请添加#include
第二个问题是,您应该使用 %p
来打印指针。
生成的代码是
#include <stdio.h>
int main(void)
{
float x;
x=6.5;
printf("Value of x is %f, address of x %p\n", x, (void *) &x);
return 0;
}