arminb arminb - 3 months ago 17
C Question

Cast void* to struct*

I have this struct:

typedef struct
{
UINT8 a;
UINT8 len;
BYTE *data;
} MyStruct;


and this binary array [0x00, 0x03, 0x08, 0x09, 0x0a] which is assigned to a void* variable "BINDATA".

How can I cast BINDATA to MyStruct and be able to access its "data" field?

I tried:

MyStruct *myStruct = (MyStruct*) BINDATA;


After that I was able to access:

myStruct->a; //gave me 0x00
myStruct->len; //gave me 0x03


But I could not access

myStruct->data;


without memory access violation. I guess this is because "data" address pointer gets set to 0x08 and not its value.

Answer

Instead of BYTE *data you should use BYTE data[0] or (if your compiler doesn't like this) BYTE data[1]. The difference between pointer and array here is crucial - array is "data that is right here" while pointer is "data somewhere else" which is not your case.