Sizeof(char[]) in C

后端 未结 8 1788
情深已故
情深已故 2021-01-17 18:15

Consider this code:

 char name[]=\"123\";
 char name1[]=\"1234\";

And this result

The size of name (char[]):4
The size of n         


        
相关标签:
8条回答
  • 2021-01-17 18:52

    In C, string literals have a null terminating character added to them.

    Your strings,

     char name[]="123";
     char name1[]="1234";
    

    look more like:

     char name[]="123\0";
     char name1[]="1234\0";
    

    Hence, the size is always plus one. Keep in mind when reading strings from files or from whatever source, the variable where you store your string, should always have extra space for the null terminating character.

    For example if you are expected to read string, whose maximum size is 100, your buffer variable, should have size of 101.

    0 讨论(0)
  • 2021-01-17 18:53

    Because there is a null character that is attached to the end of string in C.

    Like here in your case

    name[0] = '1'
    name[1] = '2'
    name[2] = '3'
    name[3] = '\0'
    
    name1[0] = '1'
    name1[1] = '2'
    name1[2] = '3'
    name1[3] = '4'
    name1[4] = '\0'
    
    0 讨论(0)
提交回复
热议问题