简体   繁体   中英

How can i get value of the structure element by it's pointer in C?

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, eg

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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