Reputation: 9
My problem is that I need have the potential to store a number of courses each with a name, and in a course is a number of sections, and a number of students in each section each with a name (obviously), and each student has a number of assignments of type float
.
So far I created a nested structure:
struct Student {
float *Assignments;
};
struct Section {
char Student_Name[30];
struct Student *Students;
};
struct Course {
char Course_Name[10];
struct Section *Sections;
};
struct Test_Cases {
struct Course *Courses;
};
Have a pointer to the root structure:
struct Test_Cases *ptr;
And seemingly allocated memory to the root structure and courses with:
ptr = (struct Test_Cases *)malloc(*Num_Cases * sizeof(struct Test_Cases));
ptr->Courses = (struct Course *)malloc(*Num_Courses * sizeof(struct Course));
Is the way I'm going about this correct? Thanks.
Upvotes: 1
Views: 79
Reputation: 144750
For all these structures, it would be better to add an integer member containing the number of elements allocated for the array:
struct Student {
char Student_Name[30];
size_t Num_Assignments;
float *Assignments;
};
struct Section {
char Section_Name[30];
size_t Num_Students;
struct Student *Students;
};
struct Course {
char Course_Name[10];
size_t Num_Sections;
struct Section *Sections;
};
struct Test_Cases {
size_t Num_Courses;
struct Course *Courses;
};
When allocating these arrays, it is safer to use calloc()
to get zero inintialized memory and to always test for memory allocation failure:
#include <stdlib.h>
struct Test_Cases *allocate_test_cases(int Num_cases, int Num_courses) {
struct Test_Cases *ptr = calloc(Num_Cases, sizeof(*ptr));
if (ptr == NULL)
return NULL;
ptr->Num_Courses = Num_Courses;
ptr->Courses = calloc(Num_Courses, sizeof(*ptr->Courses));
if (ptr->Courses == NULL) {
free(ptr);
return NULL;
}
...
}
Upvotes: 0
Reputation: 148910
Fortunately, your requirement does not involve any dynamicaly allocated multidimensional array, because it is far from easy in C language.
Here you only need to allocate various arrays of structures. There are 2 common ways to allocate arrays in C:
uninitialized memory:
struct Test_Cases* ptr = malloc(*Num_Cases * sizeof(struct Test_Cases));
or (IMHO better):
struct Test_Cases* ptr = malloc(*Num_Cases * sizeof(*ptr));
Remember: you should not cast malloc in C
zero initialized memory:
struct Test_Cases* ptr = calloc(*Num_Cases, sizeof(struct Test_Cases));
or:
struct Test_Cases* ptr = calloc(*Num_Cases, sizeof(*ptr));
malloc
is slightly faster, because its skips the 0 initialization part, but having that initialization may help to write shorter code in which case it should be prefered.
Upvotes: 0