【问题标题】:Accessing arrays using pointers使用指针访问数组
【发布时间】:2013-08-30 05:40:40
【问题描述】:

我在一个项目中遇到了以下代码 sn-p 并且不确定如何计算变量“response”的值。在这里我们可以看到,pic_data 包含两个一维数组,但“response”将这两个一维数组作为二维数组访问。 谁能解释一下这是如何工作的?

注意:下面的代码不是更大代码块的完整代码sn-p。

#define MAX 100
#define MAXBUF 100

u32 response;
u32 index;

typedef struct {
    u16         flag;   
    u16         status;  
} __attribute__ ((packed)) register;

typedef struct
{
    register      *rq[MAX];
    u64            buf[MAXBUF];

}Data;

Data *pic_data;



void getres(Data *pic_data) {
    response = *((u32*)&(pic_data->rq[index][pic_data->buf[index]]));
}

【问题讨论】:

  • 我添加了“c”标签,假设这是 C 代码。如果不是(可能是 C++?),请相应地更新标签。用编程语言标记的问题可能会得到更多关注。

标签: c arrays pointers structure


【解决方案1】:

该行不是访问二维数组,而是访问一维指针数组,然后取消引用它得到的指针。

让我们把它分解成几个步骤。开始于:

response = *((u32*)&(pic_data->rq[index][pic_data->buf[index]]));

我们可以改写为:

register *r = pic_data->rq[index]; // figure out which element of 'rq' to use
u64 offset = pic_data->buf[index]; // figure out what offset to use from 'buf'
response = *(u32 *)&r[offset];     // get the right register and extract value
                                   // into a 32-bit word

编者注:register 是保留字,请勿将其用作类型名称。您的函数参数pic_data 也会隐藏同名的全局变量。在外面小心点!

【讨论】:

    猜你喜欢
    • 2013-06-29
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多