-1

I need to read in some data from a csv file, and store each component into a struct.

The csv file has the following headers: name, last name, phone number, age

The csv file has an unknown number of records, and I want to create a dynamic array of pointers to structs to store this data.

I started with this:

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


}

But now I am absolutely stuck and have no idea how to proceed. Please help!

6
  • 1
    Does this answer your question? Allocating memory for a Structure in C Commented Aug 20, 2021 at 15:43
  • 1
    Or this one Commented Aug 20, 2021 at 15:44
  • 1
    @Aquila Search [c] csv realloc for some examples. Commented Aug 20, 2021 at 15:46
  • 1
    Not necessarily the question you asked about, but: you've got a bunch of unnecessary extra pointer levels in your person_t type. You want int age, not int *age. You might want char *name and char *last_name, but those will require allocation, too, so for a start maybe go with char name[10] and char last_name[20]. Not sure about the phone number. Commented Aug 20, 2021 at 15:50
  • 1
    You need to decide whether you want an array of pointers to your structures, or just an array of your structures. The simpler array of structures will be easier at first, which will be person_t *storage. Commented Aug 20, 2021 at 15:54

1 Answer 1

0

You probably want something like this:

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

This is not complete code, just an outline of what you could do. Also there are no error checks for malloc for brevity.

Sign up to request clarification or add additional context in comments.

1 Comment

And the OP said "The csv file has an unknown number of records", so pretty soon there'll be an opportunity to learn about realloc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.