Search code examples
arrayscvariablesstructchar

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


int main()
{
    struct Student_struct {
        char name[40];
        int age;
        float grade;
    };

    struct Student_struct student;

    printf("---------------------Student-----------------------\n\n\n");
    student.name[] = "person";
    student.age = 20;
    student.grade = 7.5;
    
    return 0;
}

I got the following error: Expected expression before ']'

I know I can use strcpy(student.name, "person") or student.name[6] = "person", but why cannot just code it as student.name[] = "person"? What is the logic behind this?


Solution

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