私は 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 を使用しています。