Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset an array that comes from struct

Tags:

c

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};

like image 639
Juno Avatar asked Nov 21 '25 10:11

Juno


1 Answers

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.

like image 120
alinsoar Avatar answered Nov 22 '25 23:11

alinsoar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!