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

后端 未结 3 1983
猫巷女王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: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 
    #include 
    
    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
    

提交回复
热议问题