尽管在main()之前声明了“ getline”和“ copy”函数原型,但我还是遇到了这些错误。该程序直接来自 C编程语言中的代码,因此我不确定问题出在哪里以及如何解决。
#include <stdio.h>
int getline(char line[], int maxline);
void copy(char to[], char from[]);
int main()
{
}
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;
}
void copy(char to[], char from[])
{
int i;
i = 0;
while ((to[i] = from[i]) != '\0')
++i;
}
编译器产生的确切错误是:
string_reverser.c:4:5: error: conflicting types for 'getline'
int getline(char line[], int maxline);
^~~~~~~
In file included from string_reverser.c:1:0:
c:\mingw\include\stdio.h:650:1: note: previous declaration of 'getline' was here
getline (char ** __restrict__, size_t * __restrict__, FILE * __restrict__);
^~~~~~~
string_reverser.c:27:5: error: conflicting types for 'getline'
int getline(char s[], int lim)
^~~~~~~
In file included from string_reverser.c:1:0:
c:\mingw\include\stdio.h:650:1: note: previous declaration of 'getline' was here
getline (char ** __restrict__, size_t * __restrict__, FILE * __restrict__);
^~~~~~~
答案 0 :(得分:3)
POSIX函数getline()
现在是一个标准库函数,已经(已经)在<stdio.h>
中声明(但是在编写K&R时不是标准的)。
因此,您不能在C语言中重新声明该函数。
解决方法是将您的getline函数重命名为其他名称,例如getline_new
使用此变通方法,更新后的代码如下所示,或者您可能希望切换到C ++,以便灵活地具有多个具有相同名称,但参数不同的函数,包括参数类型(多态概念)
#include <stdio.h>
int getline_new(char line[], int maxline);
void copy(char to[], char from[]);
int main()
{
}
int getline_new(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;
}
void copy(char to[], char from[])
{
int i;
i = 0;
while ((to[i] = from[i]) != '\0')
++i;
}