簡體   English   中英

有人可以解釋一下這個 C 結構語法嗎?

[英]Can someone explain me this C structure syntax?

我在這個官方 gnu gcc 網站上發現他們初始化了這樣的結構:

struct f1 {
  int x; int y[];
} f1 = { 1, { 2, 3, 4 } };

struct f2 {
  struct f1 f1; int data[3];
} f2 = { { 1 }, { 2, 3, 4 } };

起初我認為這是結構的默認初始化,但我對其進行了測試,並且在聲明時它不會自動初始化結構,所以使用它有什么意義(我當然用 gcc 編譯了我的程序)。

我試過的代碼:

#include <stdio.h>

struct a{
int x;
int y;
} a = {42, 42};

int main(void)
{
  struct a foo;

  printf("%d\n%d\n", foo.x, foo.y);
  return (0);
}

它輸出隨機未初始化的數據而不是

42
42

您的困惑似乎源於您不了解語法這一事實。

struct f1 {
  int x; int y[];
} f1 = { 1, { 2, 3, 4 } };

定義了一個名為f1變量,並初始化了它的成員。

在您的示例中,您還在全局 scope 中初始化了一個變量a ,但在main scope 中也有相同的變量a ,該變量未初始化。

我誤解了,這相當於struct f1 f1 = { 1, {2, 3, 4}}; ,他們使用同名f1的事實讓我覺得這是一種新語法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM