简体   繁体   English

C结构到void *指针

[英]C struct to void* pointer

I have a struct defined as: 我有一个结构定义为:

typedef struct {
   int type;
   void* info;
} Data;

and then i have several other structs that i want to assign to the void* using the following function: 然后我想使用以下函数将其他几个结构分配给void *:

Data* insert_data(int t, void* s)
{
    Data * d = (Data*)malloc(sizeof(Data));
    d->type = t;
    d->info = s;

    return d;
}

struct {
   ...
} Struct#;

then i just call 那我就打电话

insert_data(1, variable_of_type_Struct#);

When i compile this it gives a warning 当我编译时,它发出警告

warning: assignment from incompatible pointer type

i tried to cast the variable in the insert to (void*) but didn't work 我试图将插入中的变量强制转换为(void *),但没有用

insert_data(1, (void *) variable_of_type_Struct#);

How can i get rid of this warning? 我如何摆脱这个警告?

Thanks 谢谢

传递结构的地址,而不是它的副本(即,不按值传递):

insert_data(1, &variable_of_type_Struct);

Pass a pointer to the struct object: 将指针传递给struct对象:

struct your_struct_type bla;

insert_data(1, &bla);

Hope this program helps! 希望该程序对您有所帮助!

#include <stdio.h>
#include <stdlib.h>

typedef struct {
   int type;
   void* info;
} Data;

typedef struct {
    int i;
    char a;
    float f;
    double d;  
}info;

Data* insert_data(int t, void* s)
{
    Data * d = (Data*)malloc(sizeof(Data));
    d->type = t;
    d->info = s;

    return d;
}

int main()
{
    info in; 
    Data * d;
    d = insert_data(10, &in);

    return 0;
}

I'm not quite sure what this was: 我不太确定这是什么:

struct {
   ...
} Struct#;

So, I cleaned up your program a little bit and got no warnings, after putting the address of the struct into the call, insert_data(1, &variable_of_type_Struct); 因此,在将结构的地址放入调用中后,我对您的程序进行了一些清理,并且没有任何警告, insert_data(1, &variable_of_type_Struct);

#include <stdlib.h>
#include <stdio.h>

typedef struct {
    int type;
    void* info;
} Data;

Data* insert_data(int t, void* s);

Data variable_of_type_Struct;

Data* insert_data(int t, void* s)
{
    Data * d = (Data*)malloc(sizeof(Data));
    d->type = t;
    d->info = s;

    return d;
}

void test()
{
    insert_data(1, &variable_of_type_Struct);
}

insert_data waits for a void* , you put a Data . insert_data等待void* ,然后放置一个Data

insert_data(1, &variable_of_type_Struct#);

It miss a level of indirection. 它缺少间接级别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM