Search code examples
cdata-structuresstructure

How are the structure fields getting populated?


When I execute the following C program, the output is i.

struct student {
    char a[5];
};
int main() {
    struct student s[] = { "hi","hey" };
    printf("%c", s[0].a[1]);
    return 0;
}

I am unable to understand what is the function of the command struct student s[] = { "hi","hey" }; Any possible justification will be highly helpful.


Solution

  • The definition

    struct student s[] = { "hi","hey" };
    

    is equivalent to

    struct student s[2] = { { "hi" }, { "hey" } };
    

    So s[0] is the first element of the array s. And s[0].a[1] will be the second character of s[0].a.