0

I saw this sample code in an answer to How do function pointers in C work?

#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’
Community
  • 1
  • 1
Chaitanya Nettem
  • 1,209
  • 2
  • 23
  • 45

4 Answers4

5

printf lives in stdio.h, not stdlib.h.

Ed S.
  • 122,712
  • 22
  • 185
  • 265
3

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.

Including stdio.h includes a prototype of the function so that the compiler does not have to guess at its signature.

Eric J.
  • 147,927
  • 63
  • 340
  • 553
2

Add include of stdio.h:

#include <stdio.h>
René Kolařík
  • 1,244
  • 1
  • 10
  • 18
1

you have included stdlib.h instead of stdio.h. It stdio.h where printf is defined not stdlib.h. So if you chnage, the warning may be resolved.

heretolearn
  • 6,387
  • 4
  • 30
  • 53