function pointer in C strange behaviour


SUBMITTED BY: Guest

DATE: Feb. 10, 2014, 10:14 p.m.

FORMAT: Python

SIZE: 1.2 kB

HITS: 1054

  1. I have a small program that uses function pointers.
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. typedef struct _myst
  6. {
  7. int a;
  8. char b[10];
  9. }myst;
  10. void cbfunc(myst *mt)
  11. {
  12. fprintf(stdout,"called %d %s. \n",mt->a,mt->b);
  13. }
  14. int main()
  15. {
  16. /* func pointer */
  17. void (*callback)(void *);
  18. myst m;
  19. m.a=10;
  20. strcpy(m.b,"123");
  21. /* point to callback function */
  22. callback = (void*)cbfunc;
  23. /* perform callback and pass in the param */
  24. callback(&m);
  25. return 0;
  26. }
  27. The function pointer decleration
  28. void (*callback)(void*);
  29. declares a function pointer callback that takes a generic-pointer and returns void.
  30. While assigning cbfunc to callback
  31. callback = cbfunc;
  32. I get the warning
  33. warning: assignment from incompatible pointer type [enabled by default]
  34. If I use the following
  35. callback = (void*)cbfunc;
  36. It compiles without any warnings.I am using gcc (4.6.3) and compiling with CFLAGS=-g -O3 -Wall
  37. Can someone explain the reason for this?

comments powered by Disqus