Sona
Sona

Reputation: 37

Call function of type void* with arguments of type void*

I have a function which will be called from main.c. Function prototype is

void *function (void *args)
{ 
    Struct strData *data = args; 
    char* str;
    int a;
    str = data->name; 
    a = data->value;
    if (data->value == 1)
    { 
        data->value = 10;
        return data;
    }
}

And the structure definition is

Struct strData
{
    int data;
    char* name;
};

How to call above function from main ? And how can I return entire structure to a void* from a function? And how to send the value to arguments? Do I need to typecast the value of argument inside function?

Upvotes: 0

Views: 734

Answers (1)

user5561927
user5561927

Reputation:

Here is an attempt to answer what you asked:

#include <stdio.h>

struct strData
{
//changed member name from data to value due to conflicting call in funtion
    int value;
    char* name;
};

//function takes a void pointer as parameter and returns a void pointer
//I don't understand why you have written such code below.
void *function (void *args)
{ 
    struct strData *data = args; 
    char* str;
    int a;
    str = data->name; 
    a = data->value;
    if( data->value == 1)
    {   
        data->value = 10; 
    }   

    //return statement required at the end. Why?
    return data;
}

int main(){
    //created a variable of strData
    struct strData data;
    //initialised random values
    data.value = 1;
    data.name = "stackoverflow.com";
    //pass address of the variable. Why? typecast to struct. Why? Finally get value using *. Why?
    data = *(struct strData*)function(&data);
    printf("%s %d", data.name, data.value);
    return 0;
}

Answer all why questions yourself.

Upvotes: 1

Related Questions