2017-08-08 204 views
-1

我已經聲明這兩種結構:如何在C中創建一個struct數組的數組?

typedef struct { 
    int skip_lines; 
    int num; 
    int i; 
    char filename[70]; 
    char main_directory[16]; 
    char submain_directory[100]; 
} TABLE_; 

typedef struct { 
    TABLE_ radiation_insolation[7]; 
    TABLE_ radiation_radiation[5]; 
    TABLE_ winds[9]; 
    TABLE_ pressure[1]; 
    TABLE_ humidity[1]; 
    TABLE_ temperature[4]; 
} TABLES; 

在主功能我要創建的類型TABLE_的數組的數組。

TABLES tables; // this will be filled with data later 

// Now my pseudo-code: 
TABLE_ ** table_arrays; 
table_arrays[0] = tables.radiation_insolation; 
table_arrays[1] = tables.radiation_radiation; 
table_arrays[2] = tables.winds; 
table_arrays[3] = tables.pressure; 
table_arrays[4] = tables.humidity; 
table_arrays[5] = tables.temperature; 

我想要做的是table_arrays的第一個元素指向tables.radiation_insolation。 tables.radiation_radiation的下一個元素等等。我知道我現在做的方式是錯誤的,所以我問你如何正確地做到這一點?

+0

您有可以用來就像其他本地類型,如'int'類型的名稱(別名)。現在,你可以定義一個'int'數組嗎?然後你可以定義一個'TABLE_'的數組。 –

+0

「我想創建一個數組,如果類型'TABLE_'」的意思是「TABLES'類型」? –

+0

@Weather Vane:請參閱:'TABLE_radiation_insolation [7]'是類型爲TABLE_的數組。所以我需要數組的數組TABLE_ – user1141649

回答

2

如果您聲明一個指向數組的指針,則需要爲它分配空間(例如,使用malloc()),然後才能分配給元素。但是不需要使用指針,只需聲明一個數組並根據需要初始化它即可。

TABLE_ *table_arrays[] = { 
    tables.radiation_insolation, 
    tables.radiation_radiation, 
    tables.winds, 
    tables.pressure, 
    tables.humidity, 
    tables.temperature 
} 
0

正確這應該是這樣的:

void initiate(TABLES * tables){ 
    tables->radiation_insolation[0].num = 7; // initiate here 
} 
void processTables(TABLES * tables, TABLE_ * table_arrays[]){ 
    // do something with the pointer to TABLES or with pointer to TABLES_ array 
} 

TABLES tables; 
TABLE_ * table_arrays[6]; 
initiate(&tables); 
table_arrays[0] = tables.radiation_insolation; 
table_arrays[1] = tables.radiation_radiation; 
table_arrays[2] = tables.winds; 
table_arrays[3] = tables.pressure; 
table_arrays[4] = tables.humidity; 
table_arrays[5] = tables.temperature; 
processTables(&tables, table_arrays);