【问题标题】:How do I create a dynamic array of struct pointers?如何创建结构指针的动态数组?
【发布时间】:2021-10-22 03:52:35
【问题描述】:

我需要从 csv 文件中读取一些数据,并将每个组件存储到一个结构中。

csv 文件具有以下标题:姓名、姓氏、电话号码、年龄

csv 文件的记录数未知,我想创建一个指向结构的动态指针数组来存储这些数据。

我从这个开始:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv){
    typedef struct{
    char** name; 
    char** last_name; 
    int * number;
    int* age}person_t;

    person_t **storage;


}

但现在我完全陷入困境,不知道如何继续。请帮忙!

【问题讨论】:

  • 这能回答你的问题吗? Allocating memory for a Structure in C
  • 或者这个one
  • @Aquila 搜索 [c] csv realloc 获取一些示例。
  • 不一定是您问的问题,但是:您的 person_t 类型中有一堆不必要的额外指针级别。你想要int age,而不是int *age。您可能需要char *namechar *last_name,但这些也需要分配,所以一开始可以使用char name[10]char last_name[20]。不知道电话号码。
  • 您需要决定是想要一个指向结构的指针数组,还是只需要一个结构数组。更简单的结构数组一开始会更容易,即person_t *storage

标签: arrays c pointers struct dynamic


【解决方案1】:

你可能想要这样的东西:

typedef struct{
  char name[20];        // can store names of maximum length 19
  char last_name[20];   // can store last names of maximum length 19
  int number;
  int age
} person_t;


int main(int argc, char **argv){
  person_t **storage;
  ...
  // allocate an array of nbOfElements pointers to person_t
  storage = malloc(nbOfElements * sizeof(person_t*));

  for (int i = 0; i < nbOfElements; i++)
  {
     ...
     ... read one CSV line 
     ...
     // allocate memory for one person_t and store the pointer
     storage[i] = malloc(sizeof(person_t));
   
     // fill the structure
     strcpy(storage[i]->name, ...);
     strcpy(storage[i]->last_name, ...);
     storage[i]->number = ...
     storage[i]->age = ...;
  }        
}

这不是完整的代码,只是您可以做什么的概述。为简洁起见,malloc 也没有错误检查。

【讨论】:

  • OP 说“csv 文件的记录数未知”,所以很快就有机会了解realloc
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多