c - 将 printf 与指向 float 的指针一起使用会产生错误

标签 c pointers floating-point printf

当我尝试编译这段代码时:

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, &x);

^

pruebaso.c:5:9: 警告:格式“%ld”需要“long int”类型的参数,但参数 3 的类型为“float *”[-Wformat=]

我在另一个论坛上看到解决方案是先转换为 void 指针: 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 *)&x);

^

pruebaso.c:5:9:警告:格式“%ld”需要“long int”类型的参数,但参数 3 的类型为“void *”[-Wformat=]

谁能告诉我如何在没有收到警告的情况下解决它?

谢谢

最佳答案

您需要包括 <stdio.h>抑制第一个警告并使用转换为 void *并使用 %p抑制第二个警告。

在 C90 中,使用 printf()没有<stdio.h>调用未定义的行为,因为隐式声明将与实际声明不匹配,因为 printf()是可变的。 (相比之下,使用 fputs() 没问题。)在 C99 中,不允许隐式声明,但 GCC 允许您编译此类代码。

#include <stdio.h>
int main(void)
{
    float x = 6.5;
    printf("Value of x is %f, address of x %p\n", x, (void *) &x);
}

%p格式说明符用于打印指针。从技术上讲,它必须与 char * 一起使用或 void *指针。在现代系统上,这不会影响结果;但将其他指针类型传递给 %p技术上会调用未定义的行为(这是不好的)。

%ld代码中的格式是错误的,即使它适用于大多数系统。首先,它需要一个 long参数,这需要一个强制转换(即使强制转换只会在少数系统上产生影响)。其次,即使您添加了强制转换,也不能保证指针中的所有信息都保留(它可能会截断位或做其他事情)。实际上,64 位 Windows 系统是唯一一个强制转换为 long 的系统。位的排骨和类型转换在其他任何地方都可以正常工作。

所以使用%p并转换到void * .

关于c - 将 printf 与指向 float 的指针一起使用会产生错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21588258/

相关文章:

c - 递归函数代码::blocks 与 Visual Studio 2008

c - 是否可以定义没有temp/aux变量的指针? (或者这会是不好的C编码吗?)

c - 可靠地访问指针记帐数据

c++ - 从类型 'delai_assemblage*&' 的表达式对类型 'delai_assemblage' 的引用的初始化无效

python - 将 timedelta 转换为 float

sql - 如何从 SQLite 数据库中选择浮点无限文字?

c - 难以理解这段代码的工作原理(双指针)

代码审查请求,将任何内容存储到 void* 存储区域

php - 所有系统的浮点运算都一样吗?

c - 我的 pop 函数(队列)C 做错了什么