In C, a pointer to a function that returns a pointer to void (i.e., void*) involves a specific syntax for declaration and usage. Here's a breakdown:
1. Function Signature
A function that returns a void* (pointer to void) has the form:
void* my_function(parameters);
For example:
void* my_func(int x, char y) {
void* ptr = ...; // Return some address as void*
return ptr;
}
2. Pointer to the Function
To declare a pointer to such a function, use the syntax:
void* (*func_ptr)(parameters);
func_ptr is the name of the pointer.
parameters must match the function’s argument types.
Example:
// Function signature: void* my_func(int, char)
void* (*func_ptr)(int, char); // Declare pointer
func_ptr = my_func; // Assign address of my_func to the pointer
3. Full Example
#include <stdio.h>
// Function returning void*
void* my_func(int x, char y) {
void* ptr = &x; // Example: return address of x as void*
printf("Inside my_func: x=%d, y=%c\n", x, y);
return ptr;
}
int main() {
// Declare a pointer to a function that returns void* and takes (int, char)
void* (*func_ptr)(int, char);
// Assign the function to the pointer
func_ptr = my_func;
// Call the function via the pointer
void* result = func_ptr(42, 'A');
// Cast the void* to int* to demonstrate (not always safe!)
int* int_ptr = (int*)result;
printf("Value at result: %d\n", *int_ptr); // Output: 42
return 0;
}
4. Key Notes
- Syntax: The parentheses
(*func_ptr) are critical to denote a pointer to a function (not a function returning a pointer).
- Return Type:
void* is a generic pointer type. You can cast it to other pointer types (e.g., int*, char*) as needed.
- Parameters: The pointer’s parameter list (e.g.,
(int, char)) must match the function’s signature.
- Caution: Returning pointers to local variables (like
&x in the example) is unsafe because they become invalid after the function exits.
5. Advanced: Function with No Parameters
If the function takes no arguments:
void* my_func();
void* (*func_ptr)(); // Declaration
func_ptr = my_func; // Assignment
6. Common Mistakes
- Missing Parentheses:
void* *func_ptr(...) would declare a function returning a void** (pointer to a void pointer), not a function pointer.
- Parameter Mismatch: The pointer’s parameter types must exactly match the function’s.
This pattern is useful for callback functions, generic interfaces, or low-level systems programming where type erasure is needed.