何时/为什么'\ 0'需要标记(char)数组的结尾?

Str*_*ict 5 c string null-terminated

所以我刚刚阅读了一个如何创建表示字符串的字符数组的示例.

将null字符\0放在数组的末尾以标记数组的结尾.这有必要吗?

如果我创建了一个char数组:

char line[100]; 
Run Code Online (Sandbox Code Playgroud)

并说出这个词:

"hello\n"
Run Code Online (Sandbox Code Playgroud)

在其中,字符将放在前六个索引line[0]- line[6]所以数组的其余部分将填充空字符?

这本书说,这是一个约定,例如字符串常量"hello\n"放在一个字符数组中并以终止\0.

也许我不完全理解这个话题,并且很乐意启蒙.

AnT*_*AnT 10

\0字符不标记"数组的结尾".该\0字符标记存储在char数组中的字符串的结尾,如果(且仅当)char数组用于存储字符串.

char数组只是一个char数组.它存储独立的整数值(char只是一个小整数类型).char数组不必结束\0.\0在char数组中没有特殊含义.它只是一个零值.

但有时char数组用于存储字符串.字符串是以字符结尾的字符序列\0.因此,如果要将char数组用作字符串,则必须使用a终止字符串\0.

因此,关于\0"必要" 问题的答案取决于您在char数组中存储的内容.如果要存储字符串,则必须使用a终止它\0.如果您存储的不是字符串,则\0根本没有特殊含义.


May*_*urK 6

如果您将其用作字符数组,则不需要 '\0'。但是如果你使用字符数组作为字符串,你需要放'\0'。C 中没有单独的字符串类型。

有多种方法可以声明字符数组。

前任:

char str1[]    = "my string";
char str2[64]  = "my string";
char str3[]    = {'m', 'y', ' ', 's', 't', 'r', 'i', 'n', 'g', '\0'};
char str4[64]  = {'m', 'y', ' ', 's', 't', 'r', 'i', 'n', 'g', '\0'};
Run Code Online (Sandbox Code Playgroud)

所有这些数组都有相同的字符串“我的字符串”。在 str1 和 str2 中 '\0' 字符是自动添加的,但在其他两个中,您需要显式添加。


Vla*_*cow 5

何时/为何需要 '\0' 来标记(字符)数组的结尾?

如果字符数组包含字符串,则终止零是必需的。这允许找到字符串结束的点。

至于你的例子,我认为看起来如下

char line[100] = "hello\n";
Run Code Online (Sandbox Code Playgroud)

那么对于初学者来说,字符串文字有7字符。它是一个字符串,包含终止零。该字符串文字的类型为char[7]。你可以想象它像

char no_name[] = { 'h', 'e', 'l', 'l', 'o', '\n', '\0' };
Run Code Online (Sandbox Code Playgroud)

当字符串文字用于初始化字符数组时,它的所有字符都将用作初始值设定项。因此,相对于该示例,字符串文字的七个字符用于初始化数组的前 7 个元素。数组中未由字符串文字的字符初始化的所有其他元素都将隐式由零初始化。

如果要确定字符数组中存储的字符串有多长,可以使用strlen标头中声明的标准 C 函数<string.h>。它返回数组中终止零之前的字符数。

考虑下面的例子

#include <stdio.h>
#include <string.h>

int main(void) 
{
    char line[100] = "hello\n";
    
    printf( "The size of the array is %zu"
            "\nand the length of the stored string \n%s is %zu\n",
            sizeof( line ), line, strlen( line ) );
            
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

它的输出是

The size of the array is 100
and the length of the stored string 
hello
 is 6
Run Code Online (Sandbox Code Playgroud)

在 C 中,您可以使用字符串文字来初始化字符数组,不包括字符串文字的终止零。例如

char line[6] = "hello\n";
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您可能不会说该数组包含字符串,因为存储在数组中的符号序列没有终止零。