为什么我们需要在C中的字符数组末尾添加'\ 0'(null)?

Shu*_*hya 11 c arrays string algorithm char

为什么我们需要在C中的字符数组末尾添加'\ 0'(null)?我在K&R 2(1.9字符数组)中读到过它.书中找到最长字符串的代码如下:

#include <stdio.h>
#define MAXLINE 1000
int readline(char line[], int maxline);
void copy(char to[], char from[]);

main() {
    int len;
    int max;
    char line[MAXLINE];
    char longest[MAXLINE];
    max = 0;
    while ((len = readline(line, MAXLINE)) > 0)
        if (len > max) {
            max = len;
            copy(longest, line);
        }
    if (max > 0)
        printf("%s", longest);
    return 0;
}

int readline(char s[],int lim) {
    int c, i;
    for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
        s[i] = c;
    if (c == '\n') {
        s[i] = c;
        ++i;
    }
    s[i] = '\0'; //WHY DO WE DO THIS???
    return i;
}

void copy(char to[], char from[]) {
    int i;
    i = 0;
    while ((to[i] = from[i]) != '\0')
        ++i;
}
Run Code Online (Sandbox Code Playgroud)

我的问题是为什么我们将字符数组的最后一个元素设置为'\ 0'?没有它,该程序工作正常...请帮助我...

NPE*_*NPE 15

您需要结束C字符串,'\0'因为这是库知道字符串结束的位置(在您的情况下,这是copy()函数所期望的).

没有它,该程序工作正常......

没有它,您的程序具有未定义的行为.如果程序碰巧做了你期望它做的事情,你就是幸运的(或者说,不幸的是,因为在现实世界中未定义的行为将选择在最不方便的情况下表现出来).