Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

void * typed function parameter

Tags:

c

pthreads

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?

like image 334
Rapidistul Avatar asked Jan 09 '15 01:01

Rapidistul


People also ask

What is void * parameter?

When used for a function's parameter list, void specifies that the function takes no parameters. When used in the declaration of a pointer, void specifies that the pointer is "universal." If a pointer's type is void* , the pointer can point to any variable that's not declared with the const or volatile keyword.

What does * mean in Python function parameters?

What does * mean in Python function parameters? It means that parameter(s) that comes after * are keyword only parameters. Consider the following: def test(delay, result=None, *, loop=None): print(delay, result, loop)27-Aug-2019.

What is void * in C?

The void pointer in C is a pointer that is not associated with any data types. It points to some data location in the storage. This means that it points to the address of variables. It is also called the general purpose pointer. In C, malloc() and calloc() functions return void * or generic pointers.

Does void take parameters?

type function-name (formal parameter type list); A void function with value parameters are declared by enclosing the list of types for the parameter list in the parentheses. To activate a void function with value parameters, we specify the name of the function and provide the actual arguments enclosed in parentheses.


2 Answers

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 it 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
}
like image 174
haccks Avatar answered Oct 20 '22 21:10

haccks


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.

like image 27
Iharob Al Asimi Avatar answered Oct 20 '22 22:10

Iharob Al Asimi