4

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?

2
  • Are there any errors or is it just a silent fail? Commented Apr 29, 2015 at 16:21
  • You should not even be able to run that code. It will give you errors since you did not initialize record list[] properly. Commented Apr 29, 2015 at 16:27

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Could you explain why does sizeof(list) returns 16 when initialized the wrong way?
Thank you.. now I'm seeing the issue
I'm glad if the answer helped :)
3

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

1 Comment

Thank you... I didn't see this warnings... ideone compiled it as normal code