Why can't I just use this array without specifying its size?

Solution 1:

The array size is already defined in the struct declaration. Using square brackets after the declaration will access an element in the array, hence the error.

Solution 2:

In C, you cannot assign whole arrays in run-time, there's no sound rationale for it, the language was simply designed that way. You can only set all items in an array during initialization. Similarly, you cannot return arrays from functions.

In this case the simple fix is strcpy(student.name, "person");

However, while you cannot assign whole arrays in run-time, you can assign whole structs. That's a possible work-around - by creating a temporary compound literal struct, we can do this:

student = (struct Student_struct){ .name = "person", .age=20, .grade=7.5 };

Solution 3:

I know I can use strcpy(student.name, "person") or student.name[6] = "person"

Fine, but do you know that the latter will not do what you expect?

An array is not a first class citizen in C. Full stop. You cannot have an array as the left member of an assignment simply because the C language does not allow it.

So when you use student.name[6] this is not an array of 6 character, but only the seventh character. It is allowed by the language, because a character is a numeric type and that a pointer can be converted to an int.

So student.name[6] = "person" first gets a pointer to the first element of the litteral string "person" converts(*) it to an integer value (which may already be implementation defined if pointers are larger than ints) and then tries to store that into a single char which invokes undefined behaviour if char is not unsigned. Is that really what you knew?


(*) In fact it is even worse because the language requires an explicit cast to convert a pointer to an arithmetic value so this code should at least raise a warning and warnings are not to be ignored. So as it violates a constraint the code is not valid C. Nevertheless, all common implementations that I know will either stop if asked to treat this warning as an error, or will continue the way I described above if not.

Solution 4:

The lack of size is not the issue. Specifying a size won't help.

The problem is that you are trying to assign to an array. That's not allowed. You'll need to use strcpy or the like.

strcpy(student.name, "person");

In this particular case, you can initialize the array rather than assign to it.

struct Student_struct student = {
   .name  = "person",
   .age   = 20,
   .grade = 7.5
};