C语言 为什么在字符串数组中添加空字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16995440/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:37:44  来源:igfitidea点击:

Why adding a Null Character in a String array?

carraysstringcharacter-arrays

提问by Anurag-Sharma

I know that we have to use a null character to terminate a string array like this:

我知道我们必须使用空字符来终止这样的字符串数组:

char str[5] = { 'A','N','S','
char str1[5]="ANS";
' };

But I just wanted to know why is it essential to use a null character to terminate an array like this?

但我只是想知道为什么必须使用空字符来终止这样的数组?

Also why don't we add a null charater to terminate these :-

另外,我们为什么不添加一个空字符来终止这些:-

    char source[]="Test";  // Actually: T e s t ##代码## ('##代码##' is the NULL-character)
    char dest[8];

    int i=0;
    char curr;

    do {
       curr = source[i];
       dest[i] = curr;
       i++;
       } while(curr); //Will loop as long as condition is TRUE, ie. non-zero, all chars but NULL.

回答by Baard Kopperud

The NULL-termination is what differentiates a char array from a string (a NULL-terminated char-array) in C. Most string-manipulating functions relies on NULL to know when the string is finished (and its job is done), and won't work with simple char-array (eg. they'll keep on working past the boundaries of the array, and continue until it finds a NULL somewhere in memory - often corrupting memory as it goes).

NULL 终止是 C 中字符数组与字符串(以 NULL 结尾的字符数组)的区别。大多数字符串操作函数依赖于 NULL 来知道字符串何时完成(以及它的工作已完成),并赢得不能使用简单的字符数组(例如,它们将继续工作超过数组的边界,并继续直到它在内存中的某处找到 NULL - 通常会在运行时破坏内存)。

In C, 0 (the integer value) is considered boolean FALSE - all other values are considered TRUE. if, forand whileuses 0 (FALSE) or non-zero (TRUE) to determent how to branch or if to loop. char is an integer type, an the NULL-character (\0) is actually and simply a char with the decimal integer value 0 - ie. FALSE. This make it very simple to make functions for things like manipulating or copying strings, as they can safely loop as long as the character it's working on is non-zero (ie. TRUE) and stop when it encounters the NULL-character (ie. FALSE) - as this signifies the end of the string. It makes very simple loops, since we don't have to compare, we just need to know if it's 0 (FALSE) or not (TRUE).

在 C 中,0(整数值)被认为是布尔值 FALSE - 所有其他值都被认为是 TRUE。 ifforwhile使用 0 (FALSE) 或非零 (TRUE) 来决定如何分支或是否循环。char 是整数类型,NULL 字符 (\0) 实际上只是一个具有十进制整数值 0 的字符 - 即。错误的。这使得为​​诸如操作或复制字符串之类的事情制作函数变得非常简单,因为只要它正在处理的字符非零(即 TRUE),它们就可以安全地循环,并在遇到 NULL 字符时停止(即FALSE) - 因为这表示字符串的结尾。它进行了非常简单的循环,因为我们不必进行比较,我们只需要知道它是 0 (FALSE) 还是不是 (TRUE)。

Example:

例子:

##代码##

回答by Tom Studee

It isnt essentialbut if you are using any of the standard libraries, they all expect it.

这不是必需的,但如果您使用任何标准库,他们都期望它。