对不起,如果它有点傻,但我无法通过它的指针获取结构元素的值。 我应该在“out =”后面放什么才能得到“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;
}
最佳答案
您必须将 void 指针转换为类型:插入指针。
int out = 0 ;
if( d->type == 10 )
out = (( insert* )d->info)->i ;
If 语句用于检查数据保存的类型,否则您将读取未初始化的内存。
关于c - 我如何通过 C 中的指针获取结构元素的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23427086/