Search code examples
arrayscstruct

why can init array in struct with array-name in C


Bellow code is for 'init array element in strcut'

  • I have doubt about .name, why it is not .name[10] = "Bob", because it is like char arrary_name = {...} instead of char array_name[#] = {...}

(updated) after reading the comments/answers, now I know this format is 'Designated initialization' in C99

typedef struct 
{
    char name[10];
    char age;
}Man;


void main()
{

    Man man1 = 
    {
        .name = "Bob", // why not .name[10] = "Bob",
        .age = 18
    };

    printf("%s\n", man1.name); // "Bob"
    printf("%d\n", man1.age);  // 18

}

Solution

  • I have doubt about .name, why it is not .name[10] = "Bob"

    It is unclear to me why you think it should be .name[10] = "Bob", so I will try to answer it in a few different ways.

    • Because the declaration char name[10]; does not create a member called "name[10]"; it creates a member called "name", and the type of that member is char[].

    • Because the type of "Bob" is char[], so you can only use it to initialize another char[], you cannot use it to initialize a char.

    • Because the type of name is char[], therefore the type of name[10] is char, so you cannot initialize it with anything but another char.

    • Because name[10] should not be initialized with anything anyway, because it is one position past the end of the array. (Valid indexes are 0 to 9, this does not include 10.)