2013-06-22 209 views
9

聲明int數組在C中,我定義如下所示的結構,並希望直列初始化。 (結構中的字段,以及初始化後都不會改變數組foos)。第一個代碼塊中的代碼正常工作。Ç - 內部結構

struct Foo { 
    int bar; 
    int *some_array; 
}; 
typedef struct Foo Foo; 

int tmp[] = {11, 22, 33}; 
struct Foo foos[] = { {123, tmp} }; 

但是,我並不真的需要tmp字段。實際上,它只會混淆我的代碼(這個例子有點簡單)。所以,相反我想聲明的的聲明中的一些陣列的值FOOS。不過,我無法得到正確的語法。也許字段應該有不同的定義?

int tmp[] = {11, 22, 33}; 
struct Foo foos[] = { 
    {123, tmp}, // works 
    {222, {11, 22, 33}}, // doesn't compile 
    {222, new int[]{11, 22, 33}}, // doesn't compile 
    {222, (int*){11, 22, 33}}, // doesn't compile 
    {222, (int[]){11, 22, 33}}, // compiles, wrong values in array 
}; 
+1

您必須使用malloc或calloc函數爲* some_array分配內存空間。 – user1929959

回答

13
int *some_array; 

在此,實際上some_array是一個指針,而不是陣列。你可以這樣定義它:

struct Foo { 
    int bar; 
    int some_array[3]; 
}; 

一件事的typedef struct Foo Foo;整點是使用Foo而不是struct Foo。您還可以使用類型定義是這樣的:

typedef struct Foo { 
    int bar; 
    int some_array[3]; 
} Foo; 
+1

另外,你提到「結構體中的字段,也不會在初始化後改變數組的foos」,那麼你可以用「const」前綴作爲它們的定義的前綴。例如'const int some_array [3];'。這將允許分配但不能修改。 – kfsone

+0

@kfsone ITYM它將允許初始化,但不允許賦值或修改 –

20

首先,有2種方式:

  • 你知道數組的大小
  • 你不知道的大小。

在第一種情況下,它是一個靜態的規劃問題,它並不複雜:

#define Array_Size 3 

struct Foo { 
    int bar; 
    int some_array[Array_Size]; 
}; 

你可以使用這個語法來填充數組:

struct Foo foo; 
foo.some_array[0] = 12; 
foo.some_array[1] = 23; 
foo.some_array[2] = 46; 

當你不知道數組的大小,這是一個動態編程問題。 你得問問大小。

struct Foo { 

    int bar; 
    int array_size; 
    int* some_array; 
}; 


struct Foo foo; 
printf("What's the array's size? "); 
scanf("%d", &foo.array_size); 
//then you have to allocate memory for that, using <stdlib.h> 

foo.some_array = (int*)malloc(sizeof(int) * foo.array_size); 
//now you can fill the array with the same syntax as before. 
//when you no longer need to use the array you have to free the 
//allocated memory block. 

free(foo.some_array); 
foo.some_array = 0;  //optional 

其次,類型定義是有用的,所以當你寫這樣的:

typedef struct Foo { 
    ... 
} Foo; 

這意味着你替換這個「結構富」的話:「富」。 所以語法將是這樣的:

Foo foo; //instead of "struct Foo foo; 

乾杯。

+0

動態數組在其擴展之一的GCC文檔中有相當好的描述:[數組長度爲零](https://gcc.gnu.org/onlinedocs/gcc /Zero-Length.html)。您可以聲明一個長度爲零的數組作爲結構的最後一個成員,並將結構放在內存中的實際數組內容之前。請注意,這只是一個擴展,並且在此處描述了實現這些擴展的標準方法。 – Palec

1

我的回答是下面的代碼段: -

int tmp[] = {11, 22, 33}; 
struct Foo foos[] = { 
    {123, tmp}, // works 
    {222, {11, 22, 33}}, // doesn't compile 
    {222, new int[]{11, 22, 33}}, // doesn't compile 
    {222, (int*){11, 22, 33}}, // doesn't compile 
    {222, (int[]){11, 22, 33}}, // compiles, wrong values in array 
}; 

以上所有的編譯問題是,由於它不是與ANSI標準兼容,總「的Foo」是具有subaggregates其中有些是括起來,而其他人則沒有。所以如果你刪除內部括號 代表數組'tmp'它將編譯沒有失敗。例如。

struct Foo foos[] = { 
    {123, tmp}, // works 
    {222, 11,22,33 }, // would compile perfectly. 
}