c - 栈的动态内存分配数组
问题描述
我有以下结构
typedef struct {
Char *name;
int age;
double balance;
} info_t;
以及以下功能
void readFile(FILE *file, info_t **arr){ }
我想解析一个 cvs 文件并将每一行(每一行包含一个名称、年龄、余额)存储到使用动态内存分配的结构数组中。我该怎么做?每行的缓冲区为 256,每个字段为 24。我想动态分配结构数组和结构内的元素。顺便说一句,语言是c。
解决方案
一种可能的方法:
typedef struct { char* name; int age; double balance; } info_t;
// prototype of functions that need to be implemented
char* get_next_line_of_file(FILE*);
info_t parse_single_line(const char*);
// readFile() returns the number of items stored in `result`; `result` is a pointer to an array of `info_t` items
size_t readFile(FILE* file, info_t** result) {
// our array is initially empty
*result = NULL;
size_t arr_size = 0;
// let's read the lines
while (true) {
char* line = get_next_line_of_file(file);
// `line` here is dynamically-allocated, so we also check that it's not NULL
if (line == NULL) { break; }
// let's parse the line
info_t parsed_line = parse_single_line(line); // here is where you malloc() space for member `name` of `info_t`
if (parsed_line.name == NULL) { break; } // `name` allocation failed
// now that we have a new record, we can add it to the `result` array
info_t* new_array = realloc(*result, sizeof(info_t) * (arr_size + 1));
// if allocation went wrong, we simply return
if (new_array == NULL) {
free(parsed_line.name); // we avoid memory leaks
break;
}
// since `new_array` is valid, we can now update `*result`
*result = new_array;
arr_size += 1; // we update array's size
// the newly-added record must be equal to the newly-parsed line
(*result)[arr_size - 1] = parsed_line;
}
return arr_size;
}
// that's how you use the previous function
int main(void) {
FILE* file = fopen(...);
info_t* arr;
size_t arr_size = readFile(file, &arr);
// let's print all records
for (size_t i = 0; i < arr_size; i += 1) {
printf("%s, %d, %lf\n", arr[i].name, arr[i].age, arr[i].balance);
}
return 0;
}
这是你想要完成的吗?
推荐阅读
- rust - 如何使用 Clap 解析文件名?
- laravel - 如何在 github 操作中更改 .env 文件中的数据库变量?
- spring-boot - Spring Boot 基于来自外部库的自定义注解动态提供 String Bean
- angular - 组件中更新出错时的 RxJS 排序顺序
- .net - wix 使用发布构建而不是正常构建
- django - 为什么我无法在我的 django 项目中看到日期较旧的数据?
- wordpress - 如何维护 wordpress 生产和开发网站?
- java - 带有 CXF (JAX-RS)、Spring 和 Tomcat(无 web.xml)的 HTTP 404
- javascript - Cookie 在触发的页面加载时消失,但在其他页面上不会消失
- apache-flink - 在 Flink 中的范式之间移动数据