So I have a structure set up like so
EDIT: PLAYERCOORDS = 1, it is defined at the beginning of my code
struct PLAYERCOORDINATESSTRUCT
{
int type, x, y;
bool isalive;
bool isconnected;
PLAYERCOORDINATESSTRUCT(int customx, int customy, bool customisalive, bool customisconnected)
{
type=(PLAYERCOORDS);
x = customx;
y = customy;
isalive = customisalive;
isconnected = customisconnected;
}
PLAYERCOORDINATESSTRUCT()
{
type=(PLAYERCOORDS);
}
};
char* bufferwithstructdata = new char[sizeof(PLAYERCOORDINATESSTRUCT)-4];
//-4 since it's missing first int
PLAYERCOORDINATESSTRUCT testdata;
memcpy(&testdata,bufferwithstructdata,sizeof(PLAYERCOORDINATESSTRUCT)-4)
I have a char buffer that is holding all of the information for one of these structs, except for the int type (the first 4 bytes of the struct)
I am trying to figure out how to properly memcpy this to a source with an offset. I found that I need to be 4 bytes off of the structure address to begin at int x. However, I found that when I tried to add 4 to the address by doing (&testdata+4), it instead added 40 to the address! Anyone have a clue as to how I might memcpy with an offset of 4 bytes to the structure, or a way that I could just offset an address by 4 bytes instead of 10 at a time?
Thanks a lot for reading.
What you want is the following:
memcpy(((char*)&testdata)+4, bufferwithstructdata, sizeof(PLAYERCOORDINATESSTRUCT)-4);
The reason is because the +
operator applied to pointers adds the integer specified times the size of the thing being pointed to. This is why adding 4 added 40 to the address. Casting to a char* before adding 4 will add 4 byte locations. Also, if you want something a bit more portable, the following would be a nice trick to do what you want:
memcpy(((int*)&testdata)+1, bufferwithstructdata, sizeof(PLAYERCOORDINATESSTRUCT)-4);
This has the benefit of adding one integer size unit to the address, regardless of the size of int
.
As Lalaland has pointed out, it would be even better to use offsetof like so:
memcpy(offsetof(PLAYERCOORDINATESSTRUCT, x), bufferwithstructdata, sizeof(PLAYERCOORDINATESSTRUCT)-4);