Question

I am working I C with two structures: Car and List

#define MAX_LEN 10
#define NUM 7
typedef struct{
     char nr[NUM];
     char model[MAX_LEN];
     char categ[];
}Car;

#define LEN 100
typedef struct{
     Car elem[LEN];
     int n;
}List;

I want to add elements of type car into the List. I have tried

void add(List l, Car c){
      l.elem[l.n] = c;
      l.n ++;
}

but when I print the list I get weird characters and I suspect here is the problem.

Was it helpful?

Solution

 void add(List* l, Car c){

        strcpy(l->elem[l->n].nr,c.nr);
        strcpy(l->elem[l->n].model,c.model);
        strcpy(l->elem[l->n].categ,c.categ);
        l->n= l->n + 1;
  }

OTHER TIPS

You can pass List by pointer and receive accordingly

// Call
add(&l,c);

//Function 
void add(List* l, Car c){
    l->elem[l->n] = c;
    l->n++;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top