打印返回结构的成员 [英] printing a member of a returned struct
问题描述
我无法打印一个从函数返回一个结构的成员:
I'm having trouble printing a member of a struct that is returned from a function:
#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 */
}
在的
打印正确的结果,但的printf
通话to_hex_string _ 的printf
在 test_hex
崩溃我的程序。到底为什么会这样?它是一个终身的问题,或者是其他什么东西?
The printf
call inside to_hex_string_
prints the correct result, but the printf
call inside test_hex
crashes my program. Why exactly is that? Is it a lifetime issue, or is it something else?
当我更换的printf
与看跌期权(to_hex_string_(12345)。A)
,我得到一个编译器调用错误:
When I replace the printf
call with puts(to_hex_string_(12345).a)
, I get a compiler error:
invalid use of non-lvalue array
这是怎么回事?
推荐答案
有是在C规则,很少生效,其中规定:
There is a rule in C which seldom comes into effect, which states:
如果试图修改的函数调用或到结果
下一个序列点之后访问它的行为是不确定的。 <子>(C99§6.5.2.2)
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()$ C后顺序点$ C>函数本身执行。您传递给
的printf指针()
是一个指针的返回值本身的的元素 - 当的printf( )
试图通过该指针访问字符串,你会得到你的崩溃。
In this case, there is a sequence point after the arguments to printf()
are evaluated and before the printf()
function itself executes. The pointer you pass to printf()
is a pointer to an element of the return value itself - and when printf()
tries to access the string through that pointer, you get your crash.
这问题是很难碰到的,因为一个函数值不是左值,所以你不能直接拿一个指向它&放大器;
This issue is hard to run into, because a function value isn't an lvalue so you can't directly take a pointer to it with &
.
这篇关于打印返回结构的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!