Skip to content

Assign values to a record array in C

An answer to this question on Stack Overflow.

Question

I've got the following problem. For a homework assignment I'm supposed to create an Heap-Array of the record "student" for 5 students and then assign some values(names etc.). Now when I try to assign values to the record the way I did it before, i get an "expression expected before {" error.

Edit:
typedef struct student_t {
char hauptfach[128];
char name[64];
int matnr;
} student;
/Edit
student *students;
students = malloc(5*sizeof(student));
students[0] = {"Info", "Max Becker", 2781356};
students[1] = {"Soziologie", "Peter Hartz", 6666666};
students[2] = {"Hurensohnologie", "Huss Hodn", 0221567};
students[3] = {"Info", "Tomasz Kowalski", 73612723};
students[4] = {"Info", "Kevin Mueller", 712768329};

But when I try to assign a single value e.g.

students[0].hauptfach = "Informatik";

the program compiles.

What am I doing wrong?

Thanks in advance,

D.

Answer

These two statements can't really go together:

1 students = malloc(5*sizeof(student));
2 students[0] = {"Info", "Max Becker", 2781356};

(1) says that you want to dynamically allocate memory at run-time.

(2) says that you want to assign the values you list to a fixed address at compile-time. Unfortunately, the compiler cannot know what the address of students[0] is ahead of time, so it cannot do what you would like.

I'd suggest you create a helper function:

void initstudent(student *s, const char hf[], const char name[], int matnr){
  strncpy(s->hauptfach, hf, MAXLEN);
  strncpy(s->name, name, MAXLEN);
  s->matnr=matnr;
}

and then apply this to each of your students.