使用K&R C示例1.9的分段故障

tal*_*ees 0 c segmentation-fault

我是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;
}
Run Code Online (Sandbox Code Playgroud)

当我编译时,我得到以下内容:

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]
Run Code Online (Sandbox Code Playgroud)

当我运行程序时,会发生这种情况:

Ĵ

on@jon-G31M-ES2L:~/c$ ./test
Hello, does this work?
Segmentation fault (core dumped)
Run Code Online (Sandbox Code Playgroud)

我使用gcc作为我的编译器.

小智 7

更改"\0"'\0'复制功能."\ 0"是一个字符串,你想要一个字符.

  • 另请注意,编译器会针对此错误发出警告 - 带回家的消息:始终阅读并根据编译器警告执行操作! (2认同)