我是 C 新手,遇到了一个示例表单 K&R C(第 1.9 节)无法正常工作的问题。这是我从示例中复制的代码,并在寻找差异时进行了检查:
#include <stdio.h>
#define MAXLINE 1000
int mygetline(char line[], int maxline);
void copy(char to[], char from[]);
// print longest input line
main() {
int len;
int max;
char line[MAXLINE];
char longest[MAXLINE];
max = 0;
while ((len = mygetline(line, MAXLINE)) > 0)
if (len > max) {
max = len;
copy(longest, line);
}
if (max > 0) // there was a line
printf("%s", longest);
return 0;
}
// getline: read a line into s, return length
int mygetline(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';
return i;
}
// copy: copy 'from' onto 'to'; assume to is big enough
void copy(char to[], char from[]) {
int i;
i = 0;
while ((to[i] = from[i]) != "\0")
++i;
}
当我编译时,我得到以下信息:
cc -Wall -g test.c -o test
test.c:9:1: warning: return type defaults to ‘int’ [-Wreturn-type]
test.c: In function ‘copy’:
test.c:45:30: warning: comparison between pointer and integer [enabled by default]
test.c:45:30: warning: comparison with string literal results in unspecified behavior [-Waddress]
当我运行程序时,会发生这种情况:
j
on@jon-G31M-ES2L:~/c$ ./test
Hello, does this work?
Segmentation fault (core dumped)
我使用 gcc 作为我的编译器。