问题
I have a function, void *Client(void *threaData){}
Can you tell me some things about void *threadData
parameter. When you use void *
parameter and why?
回答1:
void *
is a generic pointer which can point to any object type. The above function can take a pointer to any type and can return a pointer to any type.
A generic pointer can be used if it is not sure about the data type of data inputted by the user.
Example: The following function will print any data type provided the user input about the type of data
void funct(void *a, int z)
{
if(z==1)
printf("%d",*(int*)a); // If user inputs 1, then he means the data is an integer and type casting is done accordingly.
else if(z==2)
printf("%c",*(char*)a); // Typecasting for character pointer.
else if(z==3)
printf("%f",*(float*)a); // Typecasting for float pointer
}
回答2:
Suppose you want to pass an integer to the void *Client(void *threadData){}
function, so you would
int integer;
integer = SOME_VALUE;
Client(&integer);
and in the function
void *Client(void *threadData)
{
int value;
value = *(int *)threadData;
}
and since void *
can be converted to any pointer type, you can pass any data you need to the Client()
function.
来源:https://stackoverflow.com/questions/27852372/void-typed-function-parameter