Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

In this example, the function pointer fp is used to refer to the function strchr(), which is defined elsewhere. However, fp is defined without the appropriate parameter list, and the function prototype for strchr() is not visible to this program. As a result there is no type checking performed on the call to fp(12,2);.

Code Block
bgColor#FFCCCC
#include <stdio.h>
extern char *strchr();#include <string.h>

char *(*fp) ();

int main(void) {
  char *c;
  fp = strchr;
  c = fp(12,2);
  printf("%s\n",c);

}

...

Compliant Solution: (function pointers)

Properly declaring fp so it is compatible with strchr() corrects this example.

Code Block
bgColor#ccccff
#include <string.h>

char *(*fp) (cjarconst char *,int);

int main(void) {
  char *c;
  fp = strchr;
  c = fp("Hello",'H');
  printf("%s\n",c);

}

...