简体   繁体   中英

Initializing array of structs in c

I've initialized an array of structs with three items and it is showing 2 for me !!!

#include <stdio.h>

typedef struct record {
    int value;
    char *name;
} record;

int main (void) {
    record list[] = { (1, "one"), (2, "two"), (3, "three") };
    int n = sizeof(list) / sizeof(record);

    printf("list's length: %i \n", n);
    return 0;
}

What is happening here? Am I getting crazy?

Change initialization to:

record list[] = { {1, "one"}, {2, "two"}, {3, "three"} };
/*                ^        ^  ^        ^  ^          ^  */

Your initialization with (...) leaves effect similar to {"one", "two", "three"} and creates a struct array with elements { {(int)"one", "two"}, {(int)"three", (char *)0} }

comma operator in C evaluates the expressions from left to right and discard all except the last. This is the reason why 1 , 2 and 3 are discarded.

You are not initializing list properly. Putting initializing elements in () will let the compiler to treat , as comma operator instead of separator .

Your compiler should give these warnings

[Warning] left-hand operand of comma expression has no effect [-Wunused-value]
[Warning] missing braces around initializer [-Wmissing-braces]
[Warning] (near initialization for 'list[0]') [-Wmissing-braces]
[Warning] initialization makes integer from pointer without a cast [enabled by default]
[Warning] (near initialization for 'list[0].value') [enabled by default]
[Warning] left-hand operand of comma expression has no effect [-Wunused-value]
[Warning] left-hand operand of comma expression has no effect [-Wunused-value]
[Warning] initialization makes integer from pointer without a cast [enabled by default]
[Warning] (near initialization for 'list[1].value') [enabled by default]
[Warning] missing initializer for field 'name' of 'record' [-Wmissing-field-initializers]

Initialization should be done as

 record list[] = { {1, "one"}, {2, "two"}, {3, "three"} };  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM