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'?没有它,该程序工作正常...请帮助我...
| 归档时间: |
|
| 查看次数: |
16684 次 |
| 最近记录: |