About string length, terminating NUL, etc

后端 未结 4 2285
-上瘾入骨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:38

    Answer 1: In code 1 you have a char array that is not a string; in code 2 you have a char array that is also a string.

    Answer 2: A string is a char array in which (at least) one element has the value 0; if you leave the size part empty, the compiler will automatically fill it with the minimum possible value.

    char astring[] = "foobar"; /* compiler automagically uses 7 for size */
    printf("%d\n", (int)sizeof astring);
    

    Answer 3: a char array in which one of the elements is NUL is a string; a char array where no elements are NUL is not a string.

    Answer 4: an array defined to hold two elements (char c[2];) cannot hold three elements. If it is going to be a string it can only be the empty string or a string with 1 character.

提交回复
热议问题