void * typed function parameter

时光怂恿深爱的人放手 提交于 2021-02-04 13:44:23

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!