索引以获取结构的访问成员.C编程 [英] Indexing to get access members of a structure. C programming

查看:43
本文介绍了索引以获取结构的访问成员.C编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个结构

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

哪里

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

当函数GET_MEM"将结构MEMBERS"的地址返回给X_mem时,我需要访问mem1和mem2这两个值.我的意思是:

I need to access both values mem1 and mem2, when a function "GET_MEM" returns the address of the structure "MEMBERS" to X_mem. What I mean is this:

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

我希望 value1 给出 0x15,而 value2 给出 12.

I want value1 to give 0x15, and value2 gives 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.

推荐答案

您需要转换 GET_MEM() 返回的错误类型的指针:

You need to cast the incorrectly typed pointer returned by GET_MEM():

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

这篇关于索引以获取结构的访问成员.C编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆