我是c语言的新手。所以,我从Brian Kernighan和Dennis Ritchie的书(The C programming language)中复制了代码。我正在复制pg32示例。当我收到此错误时:
pg32.c: In function ‘int main()’:
pg32.c:16:23: error: type mismatch with previous external decl of ‘char longest []’ [-fpermissive]
pg32.c:7:6: error: previous external decl of ‘char longest [1000]’ [-fpermissive]
pg32.c: In function ‘int getl()’:
pg32.c:33:20: error: type mismatch with previous external decl of ‘char line []’ [-fpermissive]
pg32.c:6:6: error: previous external decl of ‘char line [1000]’ [-fpermissive]
pg32.c: In function ‘void copy()’:
pg32.c:50:20: error: type mismatch with previous external decl of ‘char line []’ [-fpermissive]
pg32.c:6:6: error: previous external decl of ‘char line [1000]’ [-fpermissive]
pg32.c:50:31: error: type mismatch with previous external decl of ‘char longest []’ [-fpermissive]
pg32.c:7:6: error: previous external decl of ‘char longest [1000]’ [-fpermissive]
我重新输入代码4次,同样的错误。我不确定,但我认为这是遗留问题。
#include<stdio.h>
#define MAXLINE 1000
int max;
char line[MAXLINE];
char longest[MAXLINE];
int getl(void);
void copy(void);
int main()
{
int len;
extern int max;
extern char longest[];
max =0;
while((len =getl()) > 0)
if(len > max){
max = len;
copy();
}
if(max > 0)
printf("%s", longest);
return 0;
}
int getl(void)
{
int c, i;
extern char line[];
for(i =0; i < MAXLINE-1 &&
(c=getchar()) != EOF && c != '\n'; ++i)
line[i] =c;
if(c=='\n'){
line[i] = c;
++i;
}
line[i] ='\0';
return i;
}
void copy(void)
{
int i;
extern char line[], longest[];
i=0;
while((longest[i] = line[i]) != '\0')
++i;
}
我感谢任何帮助。
答案 0 :(得分:2)
您将“line”和“long”声明为文件顶部的全局变量作为固定长度数组。然后你将它们重新声明为extern(顺便说一下,不需要这样)作为不确定长度的数组。编译器不喜欢这样,因此有两种解决方案:
extern line[]
更改为extern line[MAXLINES]
,将每extern char longest[]
更改为extern char longest[MAXLINES]
extern
声明,只使用顶部的全局变量