我在打印从函数返回的结构成员时遇到问题:
#include <stdio.h>
struct hex_string
{
char a[9];
};
struct hex_string to_hex_string_(unsigned x)
{
static const char hex_digits[] = "0123456789ABCDEF";
struct hex_string result;
char * p = result.a;
int i;
for (i = 28; i >= 0; i -= 4)
{
*p++ = hex_digits[(x >> i) & 15];
}
*p = 0;
printf("%s\n", result.a); /* works */
return result;
}
void test_hex(void)
{
printf("%s\n", to_hex_string_(12345).a); /* crashes */
}
to_hex_string_
中的 printf
调用打印出正确的结果,但是 test_hex
中的 printf
调用使我的程序崩溃.为什么会这样?是一辈子的事,还是别的?
当我用 puts(to_hex_string_(12345).a)
替换 printf
调用时,出现编译器错误:
invalid use of non-lvalue array
这是怎么回事?
最佳答案
C 中有一条很少生效的规则,它指出:
If an attempt is made to modify the result of a function call or to access it after the next sequence point, the behavior is undefined. (C99 §6.5.2.2)
在这种情况下,在评估 printf()
的参数之后和执行 printf()
函数本身之前有一个序列点。您传递给 printf()
的指针是一个指针指向返回值本身的一个元素 - 当 printf()
尝试访问穿过那个指针,你就会崩溃。
这个问题很难遇到,因为函数值不是左值,所以您不能直接使用 &
获取指向它的指针。
关于c - 打印返回结构的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7963813/