[英]How does this code in C work?
typedef struct {
char a[6];
} foo;
printf("%d", (foo*)0 + 7);
Why does this print out 42? 为什么会打印出42? How does this syntax work and what is foo* exactly?
这种语法如何工作?foo *到底是什么?
This is the version of your program that compiles: 这是程序的编译版本:
#include <stdio.h>
typedef struct {
char a[6];
} foo;
int main()
{
printf("%d", (foo*)0 + 7);
}
The output if 42 because the size of the foo
structure is 6. The expression (foo*)0 + 7
(or its equivalent &((foo*)0)[7]
) denotes therefore address 42 (0 + 6 * 7). 由于
foo
结构的大小为6,因此输出为42。因此,表达式(foo*)0 + 7
(或其等效的&((foo*)0)[7]
)表示地址42(0 + 6 * 7) 。
But actually printf("%d", (foo*)0 + 7);
但是实际上
printf("%d", (foo*)0 + 7);
is undefined behaviour (even though the output will most likely be 42
on most platforms), because for printing pointer values (an address is a pointer value) you need the %p
format specifier and you need to cast to void*
(the C standard says so). 是不确定的行为(即使在大多数平台上输出很可能是
42
),因为要打印指针值(地址是指针值),您需要%p
格式说明符,并且需要强制转换为void*
(C标准说)。
So it should be: 因此应该是:
printf("%p", (void*)((foo*)0 + 7));
but then it won't print anymore 42
but something like 0000002a
which is 42 in hexadecimal. 但随后它将不再打印
42
而是类似0000002a
(十六进制为42)的内容。
Maybe I don't understand what you are asking but this might help. 也许我不明白您的要求,但这可能会有所帮助。
typedef struct {
char a[6] {7};
} foo;
foo myFoo; // instanciate a foo object
printf("%d\n", (myFoo.a[0]) + 7); // access the first element of the array in foo
printf("%d\n", *myFoo.a + 7); // access the value of the first element's
// address in the array
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.