I am trying to convert my struct into a char*, and then back to a struct. But I guess I am missing something. Once it is returned to struct, only one attribute of the struct is correct. The rest is all wrong. Here is my code.
#include <iostream>
using namespace std;
struct INFO {
unsigned char a;
int b;
int c;
char g[121];
}inf;
int main () {
char frame[128];
INFO test1 = INFO();
test1.a='y';
test1.b=4000;
test1.c=9000;
strcpy(test1.g, "Goodbye World");
sprintf(frame,(char*)&test1);
INFO test2 = INFO();
memcpy((char*)&test2, frame, sizeof(frame)); //shouldn't test2 have test1 values?
cout << test2.a<<"\n";
cout << test2.b<<"\n";
cout << test2.c<<"\n";
cout << test2.g<<"\n";
getchar();
return 0;
}
Output:
y
-858993460
-858993460
╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
Only test2.a is correct. Am I converting it to a char* wrong, or is it the way I convert it back? Thanks
There are a few problems with this code, but the one that's causing the problem is the use of sprintf
to copy binary data from the struct to the character array: if there's a NUL byte anywhere in the struct's data the copy will stop short. In this case there's a NUL char in the struct data right after the first member, either embedded in the second member or because of padding, so only the first member is copied entirely.
Use memcpy
instead of sprintf
.
// sprintf(frame,(char*)&test1); <-- wrong
memcpy(frame, &test1, sizeof(frame));
INFO test2 = INFO();
memcpy(&test2, frame, sizeof(frame));
Another problem is that the size of the INFO structure is likely not 128 because of padding and alignment, so it cannot be copied entirely to frame
. Use the sizeof
operator to find the size.
char frame[sizeof(INFO)]; // Let compiler decide size of frame
INFO test1 = INFO();
test1.a='y';
test1.b=4000;
test1.c=9000;
strcpy(test1.g, "Goodbye World");
memcpy(frame, &test1, sizeof(INFO)); // copy memory and not string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With