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

后端 未结 3 1969
猫巷女王i
猫巷女王i 2020-12-03 17:38

I have a simple program like this:

#include 
#include 
#include 

typedef struct 
{
    int numberOfDays;
             


        
相关标签:
3条回答
  • 2020-12-03 17:55

    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.

    0 讨论(0)
  • 2020-12-03 17:56

    When you partially initialise the struct, those parts not specifically initialised are set to 0.

    So the strings do have a terminating 0 and so strlen() returns the correct value.

    #include <stdio.h>
    #include <string.h>
    
    int main(){
    int i;
        char s[10] = {'a', 'b', 'c'};
        for (i=0; i<10; i++)
            printf("%d ", s[i]);
        printf("\n%d\n", strlen(s));
        return 0;
    }
    

    Program output:

    97 98 99 0 0 0 0 0 0 0
    3
    
    0 讨论(0)
  • 2020-12-03 17:58

    The reason is that your months are indeed nul-terminated. If you have an array with 10 elements, and have an initialiser for 3 elements, then the rest is filled with 0's. If you had a month with 11 characters, the compiler would tell you. If you had a month with 10 characters, you would be in trouble because there would be no nul-termination, and the compiler wouldn't tell you.

    0 讨论(0)
提交回复
热议问题