About string length, terminating NUL, etc

后端 未结 4 2279
-上瘾入骨i
-上瘾入骨i 2020-12-11 09:18

I\'m currently learning C and I\'m confused with differences between char array and string, as well as how they work.

Question 1:

Why is the

4条回答
  •  抹茶落季
    2020-12-11 09:47

    Running source code one is undefined behavior because strlen() requires a NUL-terminated string, which c[2] = "Hi"; /* = { 'H', 'i' } */ is not. A string differs from a char array in that a string is a char array with at least one NUL byte somewhere in the array.

    The remaining answers should follow easily from this fact.

    To autosize a char array to match the size of a string literal at initialization, simply specify no array size:

    char c[] = "This will automatically size the c array (including the NUL).";
    

    Note that you cannot compare char arrays with the == operator. You have to use

    if (strcmp(c1, c2) == 0) {
       /* Equal. */
    } else {
       /* Not equal. */
    }
    

提交回复
热议问题