I've created this struct:
typedef struct {
char* id;
char* name;
int birthYear;
int finishedCourses;
double avarage;
int coursesNow;
int courses[MAX_COURSES_YEAR];
}Student;
and now I am trying to set an array of courses.
this is what I wrote:
s1.courses[] = {5,4,3,2};
and the error is:
student.c:15:13: error: expected expression before ‘]’ token
s1.courses[]={5,4,3,2};
int courses[]={5,4,3,2};
memcpy (s1.courses, courses, sizeof(courses));
Other way is to do so:
typedef struct {
char* id;
char* name;
int birthYear;
int finishedCourses;
double avarage;
int coursesNow;
int courses[];
}Student;
int courses[]={5,4,3,2};
Student *s = malloc(sizeof(Student)+sizeof(courses));
memcpy (s->courses, courses, sizeof(courses));
In this second case the advantage is that you alloc at runtime the very dimension for courses, you do not use padding space or statically fixed space for the field.
There are also other ways to do it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With