为什么我们需要在 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;
}
我的问题是为什么我们将字符数组的最后一个元素设置为'\0'? 该程序在没有它的情况下工作正常...... 请帮助我...
最佳答案
您需要以 '\0'
结束 C 字符串,因为这是库知道字符串在哪里结束的方式(并且,在您的情况下,这就是 copy()
函数期望)。
The program works fine without it...
没有它,你的程序有undefined behaviour .如果程序恰好按照您的预期执行,那么您很幸运(或者更确切地说,不幸的是,在现实世界中,未定义的行为会选择在最不方便的情况下表现出来)。
关于c - 为什么我们需要在 C 中的字符数组末尾添加一个 '\0' (null)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13904149/