Soham
Soham

Reputation: 873

Error with Function Pointers

I am using this resource to help me out with Function Pointers: here But in this code (written below), compilation on gcc says:

line 15: warning: dereferencing 'void*' pointer
line15:error:called object *foo is not a function

The code is here:

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>

void print_mess(void *ptr)
{
        char *message = ptr;
        printf("%s\n",message);
}
void main()
{
        void* foo = print_mess;
        char *mess = "Hello World";
        (*foo)((void*)mess);
}

Very simple test function to brush up my knowledge, and I am embarassed to even encounter such a problem, let alone post it on SO.

Upvotes: 3

Views: 1148

Answers (1)

bdonlan
bdonlan

Reputation: 231153

Your pointer is the wrong type. You need to use:

void (*foo)(void *) = print_mess;

It looks weird, but that's a function pointer definition. You can also typedef it:

typedef void (*vp_func)(void *);
vp_func foo = print_mess;

Upvotes: 4

Related Questions