使用void *

时间:2017-09-07 15:07:06

标签: c

我有一个将从main.c调用的函数。 函数原型是

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;
    }
}

结构定义是

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

如何从main调用上面的函数?如何从函数中将整个结构返回到void *?以及如何将值发送给参数?我是否需要对函数内部的参数值进行类型转换?

1 个答案:

答案 0 :(得分:1)

以下是尝试回答您的问题:

#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;
}

回答所有问题的原因。