How to pass parameters through a void pointer in the C language?
In C language, a void pointer can be used to pass data of any type. To pass arguments to a function, you can assign the address of the argument to a void pointer, and then in the function, obtain the value of the argument by converting the void pointer to the appropriate type.
Here is an example code showing how to use a void pointer to pass arguments to a function.
#include <stdio.h>
void printValue(void *ptr, char type) {
if (type == 'i') {
int value = *(int*)ptr;
printf("Integer value: %d\n", value);
} else if (type == 'f') {
float value = *(float*)ptr;
printf("Float value: %f\n", value);
} else {
printf("Invalid type\n");
}
}
int main() {
int intValue = 10;
float floatValue = 3.14;
printValue(&intValue, 'i');
printValue(&floatValue, 'f');
return 0;
}
In the above example, we have defined a function called printValue that takes a void pointer and a character representing the data type as parameters. Based on this character, we convert the void pointer to the corresponding type and print out the value of the parameter.
In the main function, we declare an integer variable intValue and a float variable floatValue, pass their addresses to the printValue function, and specify their data types.
Running the program will produce the following output:
Integer value: 10
Float value: 3.140000
This method allows us to use void pointers to pass different types of arguments to a function and then perform type conversion within the function as needed.
More tutorials
Swipe To Delete and Undo functionality in Android’s RecyclerView.(Opens in a new browser tab)
What is the purpose of a double pointer in the C language?(Opens in a new browser tab)
How to initialize a C language second-level pointer?(Opens in a new browser tab)
What is the concept of null in c++?(Opens in a new browser tab)
How to determine if a char array is empty in C language?(Opens in a new browser tab)