Reputation: 463
I have created a structure with a Id variable and a list of values. When I check the size before passing it to a function as a void* it is 12. Once it gets in the function it is 4. How do I keep the size the same?
Struct Code:
typedef struct
{
int id;
std::list<int> sensorValues;
}dataPacketDef;
Sending to other function code:
void SendDataBufferToServer()
{
cout << "Sending network data size: " << sizeof(dpd) << "\n";
client.writeData((void*)&dpd);
}
In the above function the size is 12 but in the receiving function the size is only 4. The struct is declared as a global variable for my main program.
Upvotes: 3
Views: 248
Reputation: 49986
before passing it to a function as a void* it is 12. Once it gets in the function it is 4
Because sizeof pointer in case of your program is 4 bytes, you cant read sizeof struct if you cast instance of your struct to void*. You might fix it by passing to your function also size of your struct ie foo(static_cast<void*>(&myStructObj), sizeof(TypeOfMyStruct))
.
[edit]
also as Lightness Races in Orbit pointed out in his answer, serializing std::list is wrong, you will only write pointers to your file/
Upvotes: 3
Reputation: 385114
In the function you are taking the size of a void*
, not of a dataPacketDef
. And, apparently, on your system sizeof(void*)
is 4 bytes. The sizeof
operator is simply type-driven: it does not do magical inspection of pointees. In fact, since you have performed type erasure with that antiquated cast, it can't.
You cannot serialise your object in this way. The list isn't flat data; its elements aren't actually part of the dataPacketDef
, but dynamically allocated. The list holds pointers to those elements. All you're doing is serialising pointers, which become immediately meaningless on the target system.
Drop this approach entirely and look into how to properly serialise objects in modern C++.
Upvotes: 3
Reputation: 9383
The size of a pointer is 4 bytes (or 8 if you were using an x64 compiler). If writeData
needs to know the size of the pointed-to object, that information will need to be passed to it somehow; a common idiom is to pass the size as a second argument. With that done, you could use a helper function template to simplify things:
template<typename T>
void writeData(Client& client, const T& obj)
{
client.writeData((void*)&obj, sizeof(obj));
}
Although as molbdnilo noted in the question comments, client.writeData()
probably still won't be able to do what you want it to due to the presence of a list
in dataPacketDef
.
Upvotes: 2
Reputation: 6296
This is correct.
A pointer always contains an address, which is 4 bytes on your machine.
Therefore a sizeof any pointer will be 4 bytes on a 32-bit addressing architecture.
Upvotes: 0