我是C的新手,並且遇到了一個K & R C(1.9節)示例工作不正常的問題。下面是我從例如複製,匆匆的代碼在一次尋找差異: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]
當我運行程序,出現這種情況:
Ĵ
[email protected]:~/c$ ./test
Hello, does this work?
Segmentation fault (core dumped)
我使用gcc作爲我的編譯器。
你可能想得到一本本世紀的書.. –
K&R是舊的,但它是一個經典的,仍然非常值得一讀。 – duskwuff