Initializing an array of structures in c

I initialized an array of structures with three elements and it shows me 2 .

#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 length: %i \n", n);
    return 0;
}

What's going on here? Am I crazy?

+4
source share
2 answers

Change initialization to:

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

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

the comma operator in C evaluates expressions from left to right and discards all but the last. That's why 1, 2and 3discarded.

+4
source

list. () , .

[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]

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

All Articles