c - Getting error when trying to malloc memory to pointer variable declared separately -


i have declared char pointer in following manner:

school *student[10];  for(i=0;i<10;i++){     *student[i] = malloc(sizeof(student));   <--- error points here } 

the error is:

incompatible types when assigning type 'struct student' type 'void*' 

does know why getting error?

but how come if allocate memory in same line star. example: student *name = malloc(sizeof(student)); why work? im bit confused

*student[i] = malloc(sizeof(school)); should student[i] = malloc(sizeof(school));

students array of pointer struct of type school. need allocate each pointer in array. when write *student[i] - dereferencing pointer i instead of allocating memory it.

and nicolasmiari pointed out, sizeof operator must apply school instead of student.

but how come if allocate memory in same line star. example: student *name = malloc(sizeof(student)); why work? im bit confused

that's different. when write student *name = malloc(sizeof(student)); both declaring pointer , initialize malloc. can both steps in single line that. alternatively, declare first, assign malloc in different line - in case must remove asterisk.

you may want refer question pointer initialization , pointer assignment.


Comments