[英]Why is the usage of printf wrong in this program?
我在C语言中的函数指针如何工作的答案中看到了此示例代码。
#import <stdlib.h>
#define MAX_COLORS 256
typedef struct {
char* name;
int red;
int green;
int blue;
} Color;
Color Colors[MAX_COLORS];
void eachColor (void (*fp)(Color *c)) {
int i;
for (i=0; i<MAX_COLORS; i++)
(*fp)(&Colors[i]);
}
void printColor(Color* c) {
if (c->name)
printf("%s = %i,%i,%i\n", c->name, c->red, c->green, c->blue);
}
int main() {
Colors[0].name="red";
Colors[0].red=255;
Colors[1].name="blue";
Colors[1].blue=255;
Colors[2].name="black";
eachColor(printColor);
}
该代码返回以下错误:
test.c: In function ‘printColor’:
test.c:21: warning: incompatible implicit declaration of built-in function ‘printf’
printf
位于stdio.h
,而不是stdlib.h
。
只是为了补充其他人所说的内容,如果C编译器遇到了一个它尚未看到原型的函数,则它将对该函数的签名做出一个假设,这通常是错误的。
包括stdio.h在内的函数均包含原型,因此编译器不必猜测其签名。
添加包含stdio.h:
#include <stdio.h>
您包含的是stdlib.h而不是stdio.h。 定义了printf的stdio.h不是stdlib.h。 因此,如果您更改内容,警告可能会解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.