2

I have a structure in c and I want to allocate memory for an array of my structure, for this I'd created a function. The problem is that only first element of array is working. If I do allocation in main, it is working.

Here is my code:

typedef struct {
    int id;
    char* name;
}Car;

void read(Car**cars){
    int n,i;
    char name[50];

    printf("Cars:"); scanf("%i",&n);

    *cars = (Car*) malloc(n * sizeof(Car));

    for(i=0;i<n;i++) {
        printf("\nCar Name[%i]: ",i);   scanf("%s",name);

       (*cars[i]).id   = i; //when i>0 then It crash here...
       (*cars[i]).name = (char*) malloc(strlen(name)+1);

        strcpy((*cars[i]).name, name);

        printf("Cars Name -> %s ", (*cars[i]).name);
    } 
}

int main() {
   Car *cars = NULL;
   read(&cars);

   return 0;
}

what I am doing wrong?

tziuka
  • 545
  • 1
  • 6
  • 23
  • Note: Please [do not cast](http://stackoverflow.com/q/605845/2173917) the return value of `malloc()`. – Sourav Ghosh Dec 17 '14 at 10:42
  • 1
    Note: it is probably better anyway to do the allocation *outside* the `read` function: that way, you'll have the allocation *and* the deletion/freeing up in the same place. –  Dec 17 '14 at 10:43
  • `*car = (Car*) malloc(n * sizeof(Car));` typo: should be `cars` right? – Dinal24 Dec 17 '14 at 10:44
  • Run your code through valgrind; it will likely show you where your mistake is, and possibly more. –  Dec 17 '14 at 10:45
  • I changed the name when I posted here...is not typo thx – tziuka Dec 17 '14 at 10:46
  • Note: In C you usually write 1 instruction by line, you should split your `printf/scanf` combos – n0p Dec 17 '14 at 10:46

1 Answers1

3
(*cars)[i].id   = i; //when i>0 then It crash here...

This should work for you.

explanation:

you allocate n elements to the value of the pointer to the cars pointer.

but you try to derefference the value of the ith pointer to a cars element.

With my correction you derefference the firsts pointer's ith cars id. what is bad coded but should do what you want.

But what you probabbly want to do is asigning multiple pointers which at all point to a single car pointer instead ;)

than your crashing line could stay at it is.

dhein
  • 6,431
  • 4
  • 42
  • 74