+ 2
Struct Pointer Address
Hi everyone, I have an issue with copying elements from a packed structure to an unpacked one. I can't correctly specify the addresses of bytes. Please help. Note that I am not able to know packed structure elements. I will have just a byte array to get information from. I mean I can't use something like: memcpy(&(up->x),&(p->c),4); So I'm trying to reach c's address. However I can't. https://code.sololearn.com/cx7T9BBCM20b/?ref=app
3 Réponses
+ 3
Onur You need to first cast the packed's pointer p to char*.
Here's why.
The size of struct packed is 1+2+4 = 7.
Let's say the stored value in pointer p is x(memory address of pckd)
Passing p+3 to memcpy causes it to start reading bytes from memory location x+7+7+7=x+21 (Pointer arithmetic),and this is not what we want.
Casting p to char* will ensure that memcpy starts reading from x+1+1+1=x+3 (memory address of pckd.c)
Thus a quick fix to your problem would be:
memcpy(up,((char*)p)+3,4);
Also note that you don't have to dereference x first then take its address(&(up->x)) since x is the first element of struct unpacked and thus up already points to it.
+ 2
Anthony Maina, can't tell you how thankful I am. Have a great day!
+ 1
Forgot to mention I can use the first address the pointer's pointing to.
memcpy(&(up->y),p,1); correctly copies the char a in packed struct to char y in unpacked struct.