简体   繁体   English

建立索引以获取结构的访问成员。 C编程

[英]Indexing to get access members of a structure. C programming

Assuming I have a struct 假设我有一个结构

typedef struct  
{ 
   unsigned char mem1; 
   unsigned char *mem2
} MEMBERS;

where 哪里

 unsigned sample = 12
 MEMBERS memvalues = {  0x15 , &sample  };

I need to access both values mem1 and mem2, when a function "GET_MEM" returns the address of the structure "MEMBERS" to X_mem. 当函数“GET_MEM”将结构“MEMBERS”的地址返回到X_mem时,我需要访问值mem1和mem2。 What I mean is this: 我的意思是:

unsigned char *X_mem = GET_MEM ( );    //function returns address of memvalues
unsigned value1 = *X-mem;
unsigned Value2 = *++X_mem;

I want value1 to give 0x15, and value2 gives 12. 我希望value1给出0x15,而value2给出12。

How can I make this work? 我怎样才能做到这一点?

NOTE: Please do not assume the above code example to be syntactically correct. 注意:请不要假设上面的代码示例在语法上是正确的。 Its just to express my intention. 它只是为了表达我的意图。 Thanks Folks. 谢谢伙计们。

You need to cast the incorrectly typed pointer returned by GET_MEM() : 您需要转换GET_MEM()返回的错误键入的指针:

const MEMBERS *some_members = (MEMBERS *) GET_MEM();
unsigned value1 = some_members->mem1;
unsigned value2 = *some_members->mem2;

Yeah, have GET_MEM() return the address of the struct. 是的,让GET_MEM()返回结构的地址。

MEMBERS *X_mem = GET_MEM( );    //function returns address of memvalues
unsigned char value1 = X_men->mem1;
unsigned char Value2 = *(X_mem->mem2);

You can't get it to work like this unless X_mem is declared as a pointer to a MEMBERS struct. 除非将X_mem声明为指向MEMBERS结构的指针,否则不能让它像这样工作。 To rely on address offsets from the beginning of a struct is dangerous and non-portable, since the compiler is free to add any number of padding bytes in the struct, anywhere after mem1. 依赖于结构开头的地址偏移是危险且不可移植的,因为编译器可以在mem1之后的任何地方随意添加任意数量的填充字节。 So the sane solution is to write MEMBERS *X_mem and then access each member through the -> operator. 因此,理智的解决方案是编写MEMBERS *X_mem ,然后通过 - >运算符访问每个成员。

If you for some reason need write code that relies on offsets like this, you need to ensure that the "padding byte pattern" is as expected, or that padding is disabled entirely. 如果由于某种原因需要编写依赖于此类偏移的代码,则需要确保“填充字节模式”符合预期,或者完全禁用填充。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM