简体   繁体   English

为什么在此程序中使用printf是错误的?

[英]Why is the usage of printf wrong in this program?

I saw this sample code in an answer to How do function pointers in C work? 在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);
}

The code returns the following error: 该代码返回以下错误:

test.c: In function ‘printColor’:
test.c:21: warning: incompatible implicit declaration of built-in function ‘printf’

printf位于stdio.h ,而不是stdlib.h

Just to add to what others have said, if the C compiler comes across a function for which it has not seen a prototype it will make an assumption about the signature of that function that is generally going to be wrong. 只是为了补充其他人所说的内容,如果C编译器遇到了一个它尚未看到原型的函数,则它将对该函数的签名做出一个假设,这通常是错误的。

Including stdio.h includes a prototype of the function so that the compiler does not have to guess at its signature. 包括stdio.h在内的函数均包含原型,因此编译器不必猜测其签名。

添加包含stdio.h:

#include <stdio.h>

you have included stdlib.h instead of stdio.h. 您包含的是stdlib.h而不是stdio.h。 It stdio.h where printf is defined not stdlib.h. 定义了printf的stdio.h不是stdlib.h。 So if you chnage, the warning may be resolved. 因此,如果您更改内容,警告可能会解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM