[英]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.