문제

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;
}
도움이 되었습니까?

해결책

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.

다른 팁

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;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top