Reputation: 33
How can I initialize array dynamically in struct Course? I need to make array of student structs.
typedef struct {
char *name;
char ID[9];
} Student;
typedef struct {
Student *students = //here
} Course;
Upvotes: 0
Views: 1265
Reputation: 8614
Student *students
is just a pointer to Student
. You cannot and should not initialize the pointer.
Method1
You need to first allocate memory for the struct and then initialize it.
// in main
Course courses;
courses.students = malloc(sizeof(Student));
if (courses.students != NULL_PTR)
{
courses.students.name = malloc(100); // 100 would be the size of the name you want to store
if (courses.students.name != NULL_PTR)
{
courses.students.name = "Default Name";
courses.students.ID = 12345;
}
}
Method2
This method removes the pointers from the structs in the first place. It changes the definition of the structure.
Since there are no pointers involved, you can safely inialize the structure on definition.
typedef struct {
char name[100];
char ID[9];
} Student;
typedef struct {
Student students;
} Course;
int main(void)
{
Course courses = {{"Default Name",12345}};
// other code here
}
Upvotes: 0
Reputation:
Initializing in a struct
declaration isn't possible, and it wouldn't make sense in C -- you don't have an object of that struct yet.
Assuming you need a variable amount of Student
s in your array, there are different ways to model that. A typical approach could look like:
typedef struct {
size_t capacity;
size_t count;
Student **students;
} Course;
With the double-pointer, this is designed to hold "references" to the Student objects (instead of the Student objects themselves). I have to guess this is what you need. You could allocate and manage that for example like this:
#define CHUNKSIZE 16 // reserve space for this many Students at once
Course *Course_create(void)
{
Course *course = malloc(sizeof *course);
if (!course) return 0;
course->capacity = CHUNKSIZE;
course->count = 0;
course->students = malloc(CHUNKSIZE * sizeof *(course->students));
if (!course->students)
{
free(course);
return 0;
}
return course;
}
int Course_addStudent(Course *course, const Student *student)
{
if (course->count == course->capacity)
{
// allocate more memory if needed
size_t newcapa = course->capacity + CHUNKSIZE;
Student **newstudents = realloc(course->students, newcapa * sizeof *newstudents);
if (!newstudents) return 0; // error
course->capacity = newcapa;
course->students = newstudents;
}
course->students[course->count++] = student;
return 1; // success
}
A proper cleanup could look like this:
void Course_destroy(Course *course)
{
if (!course) return;
free(course->students);
free(course);
}
Upvotes: 2