Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 this 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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 };
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading