+ 1

Using memcpy() to write data to structure

https://code.sololearn.com/c2MmXpa5pboj/?ref=app Can't tell why this isn't working. Looks like I didn't use memcpy function right. I get "0" printed.

16th May 2020, 8:59 PM
ogoxu
ogoxu - avatar
2 Answers
+ 2
You must have bad luck if it prints 0. Good luck would crash the program so you know something is wrong because what you're doing is undefined behavior because you're writing data that is outside the structure. You're trying to copy a variable that is 4 bytes long to a 1 byte variable, thereby overwriting 3 bytes of who knows what. Perhaps your val should be a float instead of an unsigned char?
16th May 2020, 9:16 PM
Dennis
Dennis - avatar
0
Thanks... Changed unsigned char type to float and removed castings, the code worked.
16th May 2020, 9:38 PM
ogoxu
ogoxu - avatar