K&R 第 2 版,示例 1.9 字符数组

Dee*_*bek 6 c arrays kernighan-and-ritchie

我对以下代码中的 getline() 函数和参数定义有疑问。该代码直接取自 K&R 第 1.9 章:“字符数组”。我已经在这里逐字复制了它。问题是,当我按原样编译程序时,出现三个错误(我在最后复制了这些错误)。当我在出现错误的三个地方将函数和函数参数定义更改为 get_line()(带有下划线而不是仅 getline)时,错误停止并且程序按预期运行。

我的问题是:

C 中发生了什么变化,以至于 getline() 无效,但 get_line() 是函数定义的有效名称?

#include <stdio.h>
#define MAXLINE 1000    // maximum input line size

int getline(char line[], int maxline);
void copy(char to[], char from[]);

/* print longest input line */

int main()
{
    int len;            //current line lenght
    int max;            //maximum length seen so far
    char line[MAXLINE]; //current input line
    char longest[MAXLINE];//longest line saved here

    max = 0;
    while ((len = getline(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 getline(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' into '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)

我得到的错误是:

  • ./section 1.9.1.c:4:5: 错误:'getline' 的类型冲突; int getline(int line[], int maxline);

  • ./section 1.9.1.c:17:40: 错误:函数调用的参数太少,预期为 3,有 2 while ((len = getline(line, MAXLINE)) > 0);

  • ./section 1.9.1.c:30:5: 错误:'getline' 的类型冲突 int getline(int s[], int lim)

Jon*_*oni 5

分发的 stdio 库glibc声明了一个函数,该函数也getline使用与您的签名不同的签名来调用。由于您不能声明两个具有相同名称的函数,因此编译器会出错。getline在 stdio.h中找到的冲突声明是:

   ssize_t getline(char **lineptr, size_t *n, FILE *stream);
Run Code Online (Sandbox Code Playgroud)

getline函数最初是一个 glibc 扩展,后来被包含在 POSIX.1-2008 中。它不是标准的 C 函数。

如果您正在使用,gcc您可以使用-std命令行开关获得符合标准的行为。除其他外,这隐藏了非标准函数的声明。尝试例如:

gcc -Wall -pedantic -std=c11 "section 1.9.1.c" -o "section 1.9.1"
Run Code Online (Sandbox Code Playgroud)