【发布时间】:2012-11-19 13:04:41
【问题描述】:
从尝试编写一个将基本算术翻译成英文的小程序开始,我最终构建了一个二叉树(它不可避免地非常不平衡)来表示评估的顺序。 首先,我写了
struct expr;
typedef struct{
unsigned char entity_flag; /*positive when the oprd
struct represents an entity
---a single digit or a parenthesized block*/
char oprt;
expr * l_oprd;// these two point to the children nodes
expr * r_oprd;
} expr;
但是,为了有效地表示单个数字,我更喜欢
typedef struct{
unsigned char entity_flag;
int ival;
} digit;
由于现在每个“expr”结构的“oprd”字段可能是上述任何一个struct-s,我现在将它们的类型修改为
void * l_oprd;
void * r_oprd;
然后是“中心问题”: 如何通过 void 指针访问成员? 请看以下代码
#include<stdio.h>
#include<stdlib.h>
typedef struct {
int i1;
int i2;} s;
main(){
void* p=malloc(sizeof(s));
//p->i1=1;
//p->i2=2;
*(int*)p=1;
*((int *)p+1)=2;
printf("s{i1:%d, i2: %d}\n",*(int*)p,*((int *)p+1));
}
编译器不接受注释版本! 我必须用上面杂乱的方法来做吗?
请帮忙。
PS:如你所见,上面的每个 struct-s 都有一个名为“entity_flag”的字段,因此
void * vp;
...(giving some value to vp)
unsigned char flag=vp->entity_flag;
无论 void 指向什么,都可以提取标志,这在 C 中是否允许?甚至是 C 语言中的“安全”?
【问题讨论】:
-
struct
s没有任何entity_flag -
@mux: struct "s" 是用来试验指向单独 .c 文件中结构的 void 指针;不是 entity_flag 相关的项目的一部分,希望这不是投反对票的原因
-
我没有投反对票,但您的问题并不具体。
标签: c syntax void-pointers