samedi 20 août 2022

Problem with offset in pointers, cant fugure out why the lenght need to be 5 not 4;

so im doing a simple test where i copy an int memory to a char[] and then i can copy it agin to another integer

int i = 236;

char msg[sizeof(i)];

memcpy(&msg, &i, sizeof(i));
int j;
memcpy(&j, &msg, sizeof(i));

std::cout << j << std::endl;
return 0;

this works and im only passing one int, but im trying to pass 2 different integers in the same char[], knowing that a int is 4 bytes i would do

int i = 236;
int u = 69;

char msg[sizeof(int)*2];

memcpy(&msg, &i, sizeof(int));
memcpy(&msg + 4, &u, sizeof(int));

int j;
memcpy(&j, &msg+4, sizeof(int));

std::cout << j << std::endl;
return 0;

but this dont work and only when using 5 in the offset instead of 4 it works, but it makes no sense in my brain, lets say that msg[0],msg[1],msg[2],msg[3] are used by the first integer, so msg[4],msg[5],msg[6],msg[7] would be to the other integer, can someone explain that please...

Aucun commentaire:

Enregistrer un commentaire