简体   繁体   English

使用指针访问数组

[英]Accessing arrays using pointers

I came across the below code snippet in a project and was not sure how value of variable " response " is computed. 我在项目中遇到了以下代码片段,不确定如何计算变量“ response ”的值。 Here as we can see, pic_data holds two one dimensional arrays but " response " access both the single dimensional array as two dimensional array. 如我们所见,pic_data包含两个一维数组,但“ response ”将两个一维数组都作为二维数组访问。 Can anyone please explain how this works? 谁能解释一下它是如何工作的?

Note: below code is not full fledged code snippet of a larger code block. 注意:以下代码不是较大代码块的完整代码段。

#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]]));
}

That line isn't accessing a 2D array, it's accessing a 1D array of pointers, and then dereferencing the pointer it gets out. 该行不是在访问2D数组,而是在访问1D指针数组,然后取消引用它退出的指针。

Let's break it down into steps. 让我们将其分解为几个步骤。 Starting with: 从...开始:

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

We can rewrite as: 我们可以改写为:

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

Editorial note: register is a reserved word, don't use it as a type name. 社论说明: register是保留字,请勿将其用作类型名称。 Your function paramater pic_data also shadows the global variable of the same name. 您的函数pic_datapic_data了同名的全局变量。 Be careful out there! 小心点!

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

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