gpt4 book ai didi

c - 抽象结构体数组

转载 作者:行者123 更新时间:2023-11-30 14:36:27 27 4
gpt4 key购买 nike

我正在构建一个简单的硬编码 csv 解析器,如下所示:

typedef struct {
char * id;
char * date;
} ROW;

int main(int argc, char *argv[]) {

// Load a file that is of a known csv format
// With fields separated by ","
// And allow a max line length of 255 chars
FILE * fp = fopen("test100k.csv", "r");
char* FIELD_SEPARATOR = ",";
char buffer[255];

int row_num = 0;
ROW row;
ROW * rows = malloc(sizeof(row) * 120000);

// The first line is the header so we can just skip it
(void) fgets(buffer, sizeof(buffer), fp);

while(fgets(buffer, sizeof(buffer), fp) != NULL) {

// split the row
char *token;
token = row.id = strtok(buffer, FIELD_SEPARATOR);
int num_sep_encountered = 1;

while( token != NULL ) {
token = strtok(NULL, FIELD_SEPARATOR);
switch(num_sep_encountered) {
case 1: row.date = token;
}
num_sep_encountered ++;
}

printf("ID: %s | Date: %s\n", row.id, row.date);
rows[row_num++] = row;
}

}

我想更改此设置,以便我有第二个名为 ROWS 的结构,如下所示:

typedef struct {
ROW * row;
size_t size;
} ROWS;

如何在以下三个位置创建和初始化该结构:

// initialize it -- how to do this?
ROWS rows= malloc(sizeof(row) * 120000);

// how keep appending a ROW to the ROWS in the for loop?
rows->row = row

// how to set the size
rows.size = row_num

最佳答案

多维初始化可以这样完成:

const size_t no_rows = 120000;
const size_t row_size = 100;
ROWS *rows = malloc(sizeof(*rows) * no_rows);
for(size_t i=0; i<no_rows; i++) {
rows[i].row = malloc(sizeof(*rows[0].row) * row_size);
rows[i].size = row_size;
}

记住检查malloc的返回值。

关于c - 抽象结构体数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58067816/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com