char array in structs – why does strlen() return the correct value here?

TL;DR Answer: No, this is well-defined behaviour.

Explanation: As per the C11 standard document, chapter 6.7.9, initalization,

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

In your case, you have a char array of 10 elements

 char name[10];

and you’ve supplied initializer for only 3 elements, like

{ 31, {'J', 'a', 'n'} },

So, the rest of the elements in name is initialized to 0 or '\0'. So, in this case, strlen() returns the correct result.

Note: Please do not rely on this method for null-termination of strings. In case, you’re supplying the exact number of elements as initalizer, there will be no null-termination.


EDIT:

In case the name definition is changed to char name[3] and initialized with three chars, then , as per the note above, usage of strlen() (and family) will be undefined behaviour as it will overrun the allocated memory area in search of terminating null.

Leave a Comment