user4227915
user4227915

Reputation:

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?

Upvotes: 4

Views: 6778

Answers (2)

Mohit Jain
Mohit Jain

Reputation: 30489

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.

Upvotes: 4

haccks
haccks

Reputation: 106122

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"} };  

Upvotes: 3

Related Questions