C, error: Conflicting types for getline

吃可爱长大的小学妹 提交于 2021-02-04 19:49:27

问题


Can somebody please take a look at this and tell me what is wrong. I have 3 errors. 1) error: Conflicting types for getline 2) error: too few arguments to function call, expected 3 have 2 3) error: conflicting types for getline. I'm sure I have overlooked something simple but I cannot find my error. Thank you, here is the code...

#include <stdio.h>

#define MAXLINE 1000

int getline(char line[], int maxline); /*conflicting types for getline*/
void copy(char to[], char from[]);

main(){

int len;
int max;
char line[MAXLINE];
char longest[MAXLINE];

max = 0;

while((len = getline(line, MAXLINE)) > 0)/*too few arguments to call, expected 3 have 2*/
    if (len > max){
        max = len;          
        copy(longest, line);
    }   


if (max > 0)
    //printf("longest line = %d characters\n -->", max);
    printf("%s", longest);


return 0;
}


int getline(char s[], int lim){/*conflicting types for getline*/

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;
}

}

回答1:


There's GNU function getline with the same, which is not part of C standard. Presumably, you are compiling with no -std (a specific C standard) specified that makes exposes this function's GNU declaration from <stdio.h>.

You could compile with -std=c99 or -std=c11 like:

gcc -Wall -Wextra -std=c11 gl.c

or rename your function to something like my_getline() to avoid this conflict.

Also, main()'s signature needs to be one of the standard ones. Since, you don't use commandline arguments, you can use:

int main(void) { .. }

See: What should main() return in C and C++?




回答2:


The easy answer: don't call your function getline. That name's been taken.

(I know, it's an example in K&R. So you ought to be able to use it, right? Unfortunately, no. Bugs me, too.)

The slightly longer answer: there's now a semistandard getline function, which yours conflicts with. You're getting the same kind of errors you'd get if, say, you tied to name one of your own functions printf. There may be a way to say, "I don't want to use the standard getline function, I want to use my own", but in this case, it's probably not worth it.

(On a personal note: I've been programming in C for about 35 years, and for about 34.9 of those years I've been using my own getline function, ever since I read about it in K&R. But over the past year or so I've been having to rewrite all of my programs, to call my own function fgetline instead of getline, to get around this problem.)



来源:https://stackoverflow.com/questions/37121254/c-error-conflicting-types-for-getline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!