Inserting a struct in a buffer

S

Slain

I have a buffer, which has a header and then data. There is some
leeway space between the header and the data in the buffer.

I have to add some more data which is a struct and I know the size of
it. So if I get a pointer to the beginning of the start of data, go
back the size of my struct, can I just put the address of my struct ?

Packet A -- Header + Data
Struct B --> size X bytes

Pointer_to_Data
Pointer_to_Data = Pointer_to_Data - X

Is it recommended to copy the struct or can I just pass the address of
my sturct variable. If so how?

Thanks
 
S

Salt_Peter

I have a buffer, which has a header and then data. There is some
leeway space between the header and the data in the buffer.

I have to add some more data which is a struct and I know the size of
it. So if I get a pointer to the beginning of the start of data, go
back the size of my struct, can I just put the address of my struct ?

Packet A -- Header  + Data
Struct B --> size X bytes

Pointer_to_Data
Pointer_to_Data = Pointer_to_Data - X

Is it recommended to copy the struct or can I just pass the address of
my sturct variable. If so how?

Thanks

I'm guessing you have some type of fixed-size buffer you are
collecting data in.
Passing an address is simple enough, the trouble is whether the
address means anything to the target receiving that packet.

Take a socket sending packets of data for example. The last thing you
want is meaningless data being transferred. Normally you would send
only valid data using some character count to delimit the extents of
the payload. So it makes sense to insert your struct instance in the
data portion.

Inserting the struct's address or the contents of the struct (with
padding removed) outside of what constitutes the packet's payload is
useless.

To compound the issue, a struct may well have padding in order to
align data.
so the size of an instance of Data is not neccesarily the sum of its
member's sizes.

#include <iostream>
#include <vector>

struct Data
{
char c;
int n;
double d;
};

int main()
{
std::cout << sizeof(char) << std::endl;
std::cout << sizeof(int) << std::endl;
std::cout << sizeof(double) << std::endl;

Data data;
std::cout << sizeof(data) << std::endl;
}

/*

1
4
8
16 // is not 13

*/

Thats where operator<< and operator>> enter into the design so as to
eliminate padding when inserting the data into a stream. Its pointless
to offer any more information since we have no idea how that packet is
being processed.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,169
Messages
2,570,917
Members
47,458
Latest member
Chris#

Latest Threads

Top