繁体   English   中英

C语言中的这段代码如何工作?

[英]How does this code in C work?

typedef struct {
    char a[6];
} foo;

printf("%d", (foo*)0 + 7);

为什么会打印出42? 这种语法如何工作?foo *到底是什么?

这是程序的编译版本:

#include <stdio.h>

typedef struct {
  char a[6];
} foo;


int main()
{
  printf("%d", (foo*)0 + 7);
}

由于foo结构的大小为6,因此输出为42。因此,表达式(foo*)0 + 7 (或其等效的&((foo*)0)[7] )表示地址42(0 + 6 * 7) 。

但是实际上printf("%d", (foo*)0 + 7); 是不确定的行为(即使在大多数平台上输出很可能是42 ),因为要打印指针值(地址指针值),您需要%p格式说明符,并且需要强制转换为void* (C标准说)。

因此应该是:

printf("%p", (void*)((foo*)0 + 7));

但随后它将不再打印42而是类似0000002a (十六进制为42)的内容。

也许我不明白您的要求,但这可能会有所帮助。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM