I have this simple piece of code in file test.c:
#include <stdio.h>
#include <string.h>
struct Student {
char name[10];
int grade;
};
int main(){
struct Student s = {.name = "Joe", .grade = 10}; //correct
struct Student students[10];
students[0] = {.name = "John", .grade = 10}; //error
students[1] = s; //correct
struct Student some_other_students[] = {
{.name = "John", .grade = 10}
}; //correct
students[2].grade = 8;
strcpy(students[2].name, "Billy"); //correct?!? O_o
return 0;
}
Upon compiling I get this error
test.c|14|error: expected expression before '{' token|
Shouldn't the array initialize correctly at students[0] = {.name = "John", .grade = 10};?. When initializing it this way: struct Student s = {.name = "Joe", .grade = 10}; and then setting it to the array like this students[1] = s; I get no errors. Just an assumption but could it be that {.name = "Joe", .grade = 10} expression, has no reference in memory, and an array of structures is just an array of references to already initialized structures?
But then again if the array is just a reference of initialized structures how this can work? students[2].grade = 8;?
{ students[0] = (struct Student) {.name = "John", .grade = 10}; }The outer curly brackets are optional. They just limit the lifetime of the compound literal.