[英]casting void* to struct
I know that somehow similar question was asked but I couldn't figure out the answer from it.我知道有人问过类似的问题,但我无法从中找出答案。 Now I have some specific sturcts and one generic struct with '''void*''' the problem is depending on given parameter in a function I should cast this generic pointer to pointer to struct, when I try to access members in struct compiler doesn't accept this
现在我有一些特定的 sturcts 和一个带有 '''void*''' 的通用结构,问题取决于函数中的给定参数,当我尝试访问 struct 编译器中的成员时,我应该将此通用指针转换为指向 struct 的指针不接受这个
I want to return struct gen
cointaing the data of struct a
or struct b
我想回到
struct gen
cointaing的数据struct a
或struct b
example code示例代码
typedef enum
{
chooseA = 0,
chooseB = 1,
} chooseVal;
typedef struct
{
uint16_t x1;
uint8_t x2;
uint8_t* x3;
} a;
typedef struct
{
uint16_t y1;
uint8_t y2;
uint8_t* y33;
} b;
typedef struct
{
chooseVal z;
void* object;
} gen;
void readStruct(gen* out, uint16_t val, uint16_t X1)
{
out->z==val;
if(out->z==chooseA)
{
a* A;
A=(a*)out->object;
out->object->x1 = X1;/*This is the not working line */
}
}
The specific problem is caused by you still accessing the void pointer instead of the struct pointer A
.具体问题是由于您仍在访问 void 指针而不是 struct 指针
A
。 The whole reason why you created A
must be for this purpose, so simply do A->x1 = X1;
您创建
A
的全部原因必须是为此目的,所以只需执行A->x1 = X1;
. .
However, this is needlessly complicated.然而,这是不必要的复杂。 Since both structs have indentical members and just different variable names, this is a perfect case for a
union
, which means that the struct members could be allocated together with the enum instead of somewhere else.由于两个结构体都有相同的成员和不同的变量名,这是
union
的完美案例,这意味着结构体成员可以与枚举一起分配,而不是其他地方。 With standard C you can do this:使用标准 C,您可以执行以下操作:
typedef enum { A, B } choose_val_t;
typedef union
{
struct
{
uint16_t x1;
uint8_t x2;
uint8_t* x3;
};
struct
{
uint16_t y1;
uint8_t y2;
uint8_t* y3;
};
} ab_t;
typedef struct
{
choose_val_t val;
ab_t ab;
} gen_t;
void readStruct(gen_t* out, choose_val_t val, uint16_t X1)
{
out->val = val;
switch(val)
{
case A: out->ab.x1 = X1; return ;
case B: /* something */ return ;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.