I'm not sure how I can store and modify an int using the following stucts in C. I don't think the values that I insert into a student struct are being stored. The student grade must stay void*
and I need to be able to access/modify the grade at anytime until exiting.
typedef struct student{
void *grade;
} student;
typedef struct school{
student **students;
size_t school_size;
}school;
student *student_create(int x){
student *new_student = malloc(sizeof(student));
new_student->grade = malloc(sizeof(int));
new_student->grade = &x;
return new_student;
}
school *school_create(size_t school_szie) {
school *s = (school*)malloc(sizeof(school));
s->students = (student**)malloc(sizeof(student*) * school_szie);
for (int i = 0; i < school_szie; ++i) {
s->students[i] = NULL;
}
return s;
}
void school_insert(school *s, int count, int index){
if(s->students[index] == NULL){
student *new_s = student_create(count);
s->students[index] = new_s;
}
}
void student_inc(school *s, int index){
*(int *)s->students[index]->grade = *(int *)s->students[index]->grade + 1;
}
int main(){
int a = 10;
void *ptr = &a;
printf("%d\n", *(int *)ptr);
*(int *)ptr = *(int*)ptr + 1;
printf("%d\n", *(int *)ptr);
school *s1 = school_create(5);
school_insert(s1, 2, 1); // school name, grade, index
school_insert(s1, 4, 0);
school_insert(s1, 7, 3);
printf("%d\n", *(int *)s1->students[1]->grade);
printf("%d\n", *(int *)s1->students[0]->grade);
printf("%d\n", *(int *)s1->students[3]->grade);
return 0;
}
I'm getting the following output,although the intended output of the last three lines should be 2, 4, 7.
10
11
7
7
7