簡體   English   中英

如何在C中創建結構數組的數組?

[英]How to create Array of arrays of struct in C?

我已經聲明了這兩種結構:

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的第一個元素指向table.radiation_insolation。 table.radiation_radiation的下一個元素,依此類推。 我知道我現在做的方法是錯誤的,所以我問你如何正確做?

如果聲明一個指向數組的指針,則需要為其分配空間(例如,使用malloc() ),然后才能分配給元素。 但是無需使用指針,只需聲明一個數組並根據需要對其進行初始化。

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

正確地,這應該是這樣的:

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);

暫無
暫無

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

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