I cannot understand what's wrong with my c implementation of: dynamically allocating an array of struct inside a function to use with in other functions.
The problem is my .exe stops working after reading the first struct(which is read correctly).
The struct:
struct student
{
char name1[30], name2[30];
float grade;
};
The function:
void read(int *n, struct student **a)
{
if(scanf(" %d", n) == 1)
{
int i;
*a=(struct student*)malloc((*n)*sizeof(struct student*));
for(i=0; i<*n; i++)
scanf("%29s %29s %f",(*a)[i].name1, (*a)[i].name2, &(*a)[i].grade);
//it stops working right after this line is executed
}
}
Main:
int main()
{
int n;
struct student *a;
read(&n, &a);
return 0;
}
Warrnings:
format '%s' expects argument of type 'char *', but argument 2 has type 'char (*)[30]' [-Wformat=]| format '%s' expects argument of type 'char *', but argument 3 has type 'char (*)[30]' [-Wformat=]|
Using a+i instead of a[i] doesn't change anything. I am aware &(*a) means a, but i wanted to make everything as clear as possible. I feel like there's something obviously wrong about my dynamic allocation that i'm missing. I read so many questions here, but nothing appears to solve my problem. Thanks for your time!
EDIT 1: i changed the code to the suggestions:
scanf("%29s %29s %f", a[i].name1, a[i].name2, a[i].grade);
and now i get the error below instead.
Error:
error: request for member 'name1' in something not a structure or union
EDIT 2: so, the line:
scanf("%29s %29s %f",*a[i].name1, *a[i].name2, *a[i].grade);
gives the error:
request for member 'name1' in something not a structure or union
and the line:
scanf("%29s %29s %f",(*a)[i].name1, (*a)[i].name2, (*a)[i].grade);
crashes.
EDIT 3:
scanf("%29s %29s %f", (*a)[i].name1, (*a)[i].name2, &(*a)[i].grade);
works.