How to create and read dynamic array of data type in C?

Viewed 66

I'm trying to manipulate a dynamic array of a type named car but I'm constantly getting "Segmentation Faults" or "Incompatible type" errors.

I have tried every combination of '*' and '&' and nothing seems to be working.

The struct type is defined as:

struct car{
  unsigned int id;
  char *name;
};

then it is created in main.c with:

struct car *testing;

And I'm trying to introduce data from a previously created array (cars) with a function in another file called void init_cars:

void init_cars(struct car *array[]){
  int i;
  array = malloc (SIZE * sizeof(struct car));
  for(i=0; i<SIZE;i++){
    array[i]->id=cars[i].id;
    array[i]->name=cars[i].name;
  }

The function should copy the array of cars "cars" to the new dynamic array "testing" and another function should be able to read the data of "testing" but I get Segmentation faults when doing malloc or when loading the data.

1 Answers
void init_cars(struct car **array){
  int i;
  *array = malloc (SIZE * sizeof(struct car));
  for(i=0; i<SIZE;i++){
    (*array)[i].id=cars[i].id;
    (*array)[i].name=cars[i].name;
  }

Since you are passing struct car ** you need to dereference it twice when assigning.

from main you can call at as below.

struct car *testing;
init_cars(&testing);
Related