Char array pointer to struct

Hi again!

I have an array of chars that contains a raw data byte-formatted:

 
  unsigned char* myData;


And I have a Struct like this:

1
2
3
4
5
6
7
  struct myStruct
{
      unsigned short content;
      unsigned short content2;
      unsigned short content3;
      unsigned short content4;
};


It is possible to declare a Struct and make it point to an offset of the char array without needing to make a memory copy?
Something like this:

1
2
  unsigned int offset = 123;
  _POOL_HEADER* myStruct= &myData[offset];
Last edited on
You can do this:
 
auto header = (_POOL_HEADER *)(myData + offset);
but you have to be careful how you access the data. For example, if you do something like this:
1
2
3
4
read_from_file(myData);
auto header = (_POOL_HEADER *)(myData + offset);
header->foo = 13;
write_to_file(myData);
you may find that the file stays unchanged. This is an aliasing error and it happens because the compiler attempts to optimize memory accesses as much as possible, and doesn't realize that myData and header point to overlapping regions.
> unsigned int offset = 123;
> _POOL_HEADER* myStruct= &myData[offset];
Watch out for accessing multi-byte data types such as short on an odd address. Most machines prefer (or require) that objects that are N bytes wide are stored at addresses that are even with respect to N (addr % N == 0).

If the machine really objects, you'll get a bus error.
https://en.wikipedia.org/wiki/Bus_error
its possible but not really friendly.
its easier for your scenario to just say
mystruct* msp = new mystruct[somesize];

msp[x].field = whatever;
etc;

char* cp = (char*)msp;
file.write(cp, somesize*sizeof(mystruct)); //or whatever you needed the char* for

and of course you can just cast in place for the file write / network write / whatever you were doing.
Last edited on
I also have to ask why you have
1
2
3
4
5
6
7
struct myStruct
{
      unsigned short content;
      unsigned short content2;
      unsigned short content3;
      unsigned short content4;
};

instead of
1
2
3
4
struct myStruct
{
      unsigned short content[4]
};

Topic archived. No new replies allowed.