I have a function that takes a string, an array of strings and an array of pointers and searches for a string in an array of strings and returns the corresponding pointer from an array of pointers. Since I use this for several different things, an array of pointers is declared as an array (void *), and the caller needs to know which pointers actually exist (and therefore which pointer it returns as the return value).
However, when I pass in an array of function pointers, I get a warning when compiling with -Wpedantic :
clank:
test.c:40:8: warning: assigning to 'voidfunc' (aka 'void (*)(void)') from 'void *' converts between void pointer and function pointer [-Wpedantic]
NCA:
test.c:40:8: warning: ISO C forbids assignment between function pointer and 'void *' [-Wpedantic] fptr = find_ptr("quux", name_list, (void **)ptr_list,
Here is a test file that, despite the warning, correctly prints "quux":
#include <stdio.h> #include <string.h> void foo(void) { puts("foo"); } void bar(void) { puts("bar"); } void quux(void) { puts("quux"); } typedef void (* voidfunc)(void); voidfunc ptr_list[] = {foo, bar, quux}; char *name_list[] = {"foo", "bar", "quux"}; void *find_ptr(char *name, char *names[], void *ptrs[], int length) { int i; for (i = 0; i < length; i++) { if (strcmp(name, names[i]) == 0) { return ptrs[i]; } } return NULL; } int main() { voidfunc fptr; fptr = find_ptr("quux", name_list, (void **)ptr_list, sizeof(ptr_list) / sizeof(ptr_list[0])); fptr(); return 0; }
Is there a way to fix the warning, except to not compile with -Wpedantic , or duplicate my find_ptr function, once for function pointers and once for non-function pointers? Is there a better way to achieve what I'm trying to do?
c pointers function-pointers
sagittarian
source share