2

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
  • omit the [] in void init_cars(struct car *array[]) Commented Oct 18, 2019 at 9:42

1 Answer 1

1
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);
Sign up to request clarification or add additional context in comments.

Comments

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.