2017-08-08 190 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);