c - 我如何通过 C 中的指针获取结构元素的值?

标签 c pointers structure

对不起,如果它有点傻,但我无法通过它的指针获取结构元素的值。 我应该在“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/

相关文章:

c - 通过在 C 中分配整数数组来理解这种行为

c++ - 如何使指针指向二维数组的任意数组元素?

c - realloc() 悬挂指针和未定义行为

将字符从源字符串复制到缓冲区 - C

C++ - 如何写入和读取包含对象的结构? (写入和读取二进制文件)

python - 关于防止代码重复的代码结构建议(Python、列表)

c++ - 结构/对象内的存储顺序

c - Glob函数(c)和备份文件(file~)

使用非标准头编译 C

c - 使用 NETLINK 的 VLAN 信息