首页 > 解决方案 > 栈的动态内存分配数组

问题描述

我有以下结构

typedef struct {
    Char *name;
    int age;
    double balance;
    } info_t;

以及以下功能

 void readFile(FILE *file, info_t **arr){ }

我想解析一个 cvs 文件并将每一行(每一行包含一个名称、年龄、余额)存储到使用动态内存分配的结构数组中。我该怎么做?每行的缓冲区为 256,每个字段为 24。我想动态分配结构数组和结构内的元素。顺便说一句,语言是c。

标签: ccsvmemorystructdynamic

解决方案


一种可能的方法:

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

这是你想要完成的吗?


推荐阅读