簡體   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