Reputation: 1453
I came across the below code snippet in a project and was not sure how value of variable "response" is computed. Here as we can see, pic_data holds two one dimensional arrays but "response" access both the single dimensional array as two dimensional array. 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]]));
}
Upvotes: 1
Views: 105
Reputation: 225242
That line isn't accessing a 2D array, it's accessing a 1D array of pointers, and then dereferencing the pointer it gets out.
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. Your function paramater pic_data
also shadows the global variable of the same name. Be careful out there!
Upvotes: 1