12

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:

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

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

How can i get rid of this warning?

Thanks

Nitrate
  • 349
  • 1
  • 5
  • 13

5 Answers5

15

Pass in the address of the struct, not a copy of it (i.e. not passed by value):

insert_data(1, &variable_of_type_Struct);
hmjd
  • 120,187
  • 20
  • 207
  • 252
5

Pass a pointer to the struct object:

struct your_struct_type bla;

insert_data(1, &bla);
ouah
  • 142,963
  • 15
  • 272
  • 331
4

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;
}
Sangeeth Saravanaraj
  • 16,027
  • 21
  • 69
  • 98
2

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

#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);
}
octopusgrabbus
  • 10,555
  • 15
  • 68
  • 131
0

insert_data waits for a void*, you put a Data.

insert_data(1, &variable_of_type_Struct#);

It miss a level of indirection.

md5
  • 23,373
  • 3
  • 44
  • 93