Sizeof(char[]) in C

后端 未结 8 1867
情深已故
情深已故 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:36

    Note the difference between sizeof and strlen. The first is an operator that gives the size of the whole data item. The second is a function that returns the length of the string, which will be less than its sizeof (unless you've managed to get string overflow), depending how much of its allocated space is actually used.

    In your example

    char name[]="123";
    

    sizeof(name) is 4, because of the terminating '\0', and strlen(name) is 3.

    But in this example:

    char str[20] = "abc";
    

    sizeof(str) is 20, and strlen(str) is 3.

提交回复
热议问题