Possible Duplicate:
Learning C by K&R, error when trying to compile programs from book with arrays and function callskhai trước của 'chức năng' đã ở đây trong C
Trong khi học C Ngôn ngữ lập trình bởi Brian W. Kernighan và Dennis M. Ritchie, tôi đã thử ví dụ trong phần 1.9 Mảng nhân vật. Dưới đây là các mã:
/* read a set of text lines and print the longest */
#include <stdio.h>
#define MAXLINE 1000 /* maximum input line length */
/* declare functions: getline() and copy() */
int getline(char line[], int maxline);
void copy(char to[], char from[]);
/* getline: read a line into array "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'; /* the null character whose value is 0 */
return i;
}
/* copy: copy 'from' into 'to'; assume to is big enough */
/* the return type of copy is "void" -- no value is returned */
void copy(char to[], char from[])
{
int i;
i = 0;
while ((to[i] = from[i]) != '\0') /* terminated with a \0 */
++i;
}
/* print the longest input line */
int main()
{
int len; /* current line length */
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;
}
Có hai lỗi chính:
- lỗi: mâu thuẫn loại cho 'getline'
- lỗi: khai trước của 'getline' đã ở đây
Danh sách lỗi đầy đủ có tại đây:
/Users/C/Codes/Ritchie/array_char.c:8: error: conflicting types for ‘getline’
/usr/include/stdio.h:449: error: previous declaration of ‘getline’ was here
/Users/C/Codes/Ritchie/array_char.c:13: error: conflicting types for ‘getline’
/usr/include/stdio.h:449: error: previous declaration of ‘getline’ was here
/Users/C/Codes/Ritchie/array_char.c: In function ‘getline’:
/Users//C/Codes/Ritchie/array_char.c:17: warning: comparison between pointer and integer
/Users/C/Codes/Ritchie/array_char.c:17: warning: comparison with string literal results in unspecified behavior
Tôi không chắc chắn những gì đã xảy ra, vì nó chính xác là mã giống với cuốn sách. Có thể tuyên bố các chức năng ngay từ đầu:
int getline(char line[], int maxline);
void copy(char to[], char from[]);
là có vấn đề? Cảm ơn bạn!
Vui lòng gửi thông báo lỗi thực tế (không diễn giải) – CrazyCasta
Có lý do nào để làm mọi thứ theo cách khó khăn ở đây không, hoặc bạn có thể sử dụng 'fgets' và' strcpy' thay thế không? –