Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C : function pointer and typedef problem

Tags:

People also ask

What is typedef for function pointer?

typedef is a language construct that associates a name to a type. myinteger i; // is equivalent to int i; mystring s; // is the same as char *s; myfunc f; // compile equally as void (*f)(); As you can see, you could just replace the typedefed name with its definition given above.

Can we typedef a function in C?

The typedef is a keyword used in C programming to provide some meaningful names to the already existing variable in the C program. It behaves similarly as we define the alias for the commands. In short, we can say that this keyword is used to redefine the name of an already existing variable.

Can we use typedef in function?

Simply put, a typedef can be used as a pointer that references a function.

What is typedef void in C?

typedef void (*MCB)(void); This is one of the areas where there is a significant difference between C, which does not - yet - require all functions to be prototyped before being defined or used, and C++, which does.


I have a C function that takes a function pointer as argument, it's a destructor that I'll call at the end of my program. Here is the prototype of my function :

int store_dest(void (*routine)(void *));

I want to store this function pointer into a structure with some other infos. In order to have a nice struct, I want to have a typedef to this function pointer. Here is my typedef :

typedef void (*my_destructor)(void *);

And here is my structure :

typedef struct my_struct{
  my_destructor dest;
  other_info ...
} my_struct;

During the initialization step, I want to set the "dest" field to a function of mine, here is the prototype of this function :

void* my_dummy_dest(void* foo);

The problem (in fact it's just a warning but I'd like to suppress it) occurs when I try to set the "dest" field of my structure to "my_dummy_dest" :

my_struct.dest = &my_dummy_dest;

I get a "warning: assignment from incompatible pointer type"

Same when I just compare them :

if (my_struct.dest == &my_dummy_dest)

I get a "warning: comparison of distinct pointer types lacks a cast"

But I get no warning when I set the "dest" field with another routine. I don't get why I have those warnings.