Reputation: 273
I'm trying to convert a string to a structure.the struct in first field stores number of chars present in second field. Please let me know what I'm missing in this program. I'm getting output wrongly(some big integer value)
update: Can this program be corrected to print 4 (nsize) ?
#include <iostream>
using namespace std;
struct SData
{
int nsize;
char* str;
};
void main()
{
void* buffer = "4ABCD";
SData *obj = reinterpret_cast< SData*>(buffer);
cout<<obj->nsize;
}
Upvotes: 0
Views: 140
Reputation: 50120
if you want to make an ASCII representation of a piece of data then , yes, you need to do serialization. This is not simply a matter of hoping that a human readable version of what you think of as the contents of a struct can simply be cast to that data. You have to choose a serialization format then either write code to do it or use an existing library.
Popular Choices:
I would use json - google for "c++ json library"
Upvotes: 1
Reputation: 44238
Your approach is utterly wrong. First of all binary representation of integer depends on platform, ie sizeof
of int
and endiannes of hardware. Second, you will not be able to populate char
pointer this way, so you need to create some marshalling code that reads bytes according to format, convert them to int and then allocate memory and copy the rest there. Simple approach with casting block of memory to your struct will not work with this structure.
Upvotes: 3
Reputation: 1133
In an SData object, an integer occupies four bytes. Your buffer uses one byte. Further, a character '4' is different from a binary form of an integer 4.
Upvotes: 1