1

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;
}
Entrack
  • 51
  • 1
  • 1
  • 10

2 Answers2

4

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.

this
  • 5,229
  • 1
  • 22
  • 51
1

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;
Sebastian
  • 8,046
  • 2
  • 34
  • 58
  • We are in C, so do not cast a `void*` without need. – Deduplicator May 02 '14 at 11:36
  • 2
    @Deduplicator: Sure, but here (in the oneliner) we **have** the need, haven't we? – alk May 02 '14 at 11:38
  • @Deduplicator [this](http://stackoverflow.com/questions/3559656/casting-void-pointers) is an interesting SO question to this discussion. *Plus* I'd be glad if you could lead me to a rule for your original statement. – Sebastian May 02 '14 at 11:42
  • Guys, please stop it and move it to chat, it draws to much attention on my answer ;) – Sebastian May 02 '14 at 11:45