throwawayguy throwawayguy - 4 months ago 36
C Question

C dynamic struct error

#include <stdio.h>
#include <stdlib.h>

int main()
{
int size,choice;
printf("student size:\n");
scanf("%d", &size);

typedef struct
{
int age;
double gpa;
char name[];
}STUDENT;
STUDENT *array = (STUDENT *) malloc(sizeof(STUDENT) * size);
printf("\n(1) Add a student\n(2) Delete a student\n(3) Save all students\n(4)Quit\n");
scanf("%d",&choice);
while (choice != 4){
switch (choice) {
STUDENT temp;
STUDENT *tempptr = &temp;
int cellNum;
case 1:
printf("Enter age gpa and name:\n");
scanf("%d %f %s",&tempptr->age,&tempptr->gpa,&tempptr->name);
printf("Enter cell number:\n");
scanf("%d", &cellNum);
if (cellNum > (size-1)){
printf("Invalid cell number\n");
break;
}else{
*(array + cellNum) = temp;
}
case 3:
printf("stupid c syntax rules");
FILE *p = fopen("students.txt","w");
int i = 0;
for (i=0; i<size; i++){
fprintf(p, "%d, %f, %s\n",*(array+i).age,*(array+i).gpa,*(array+i).name);
}
}
printf("\n(1) Add a student\n(2) Delete a student\n(3) Save all students\n(4)Quit\n");
scanf("%d",&choice);
}

return 0;
}


getting errors:

main.c:40:56: error: request for member 'age' in something not a structure or union

fprintf(p, "%d, %f, %s\n",(array+i).age,(array+i).gpa,(array+i).name);

^

main.c:40:71: error: request for member 'gpa' in something not a structure or union

fprintf(p, "%d, %f, %s\n",
(array+i).age,(array+i).gpa,(array+i).name);

^

main.c:40:86: error: request for member 'name' in something not a structure or union

fprintf(p, "%d, %f, %s\n",(array+i).age,(array+i).gpa,*(array+i).name);

why is this happening?
Thanks

Answer

The . operator is a higher precedence than unary * (refer here). So first (before dereferencing) the compiler is trying to find an age field in (array+i), which is not a structure, but a pointer.
You want to replace the *(array+i).age by either (array+i)->age or (*(array+i)).age.

Comments