Pergunta

Excuse me, if it is kinda silly, but I can't get value of the structure element by it's pointer. What should i put after "out = " to get "5"?

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

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

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

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

int main()
{
    Data *d;
    int out;
    insert in; 
    in.i = 5;
        d = insert_data(10, &in);
    out = /*some int*/
    getch();
    return 0;
}
Foi útil?

Solução

You have to cast the void pointer to type: insert pointer.

int out = 0 ;
if( d->type == 10 ) 
    out = (( insert* )d->info)->i ;

If statement is there to check what type Data is holding, otherwise you would be reading uninitialized memory.

Outras dicas

Assuming you want to access the newly created data and get it's value, you'll have to do a cast and access the element inside the struct, e.g.

insert* x = (insert*)(d->info);
out = x->i

Of course this is also doable in a one-liner:

out = ((insert*)(d->info))->i;
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top