problem with pointer arithmetic

O

Oliver Kowalke

Hello,
I don't know why I've to increment the cahr pointer by 12 instead of 9 in
the code below.
regards, Oliver

class message
{
private:
char buffer_[100];

struct header
{
char name[3]; // should be 3 bytes
unsigned short version; // should be 2 bytes
unsigned long data_size; // should by 4 bytes
};

public:
message()
: buffer_()
{ ::bzero( buffer_, sizeof buffer_); }

message( std::string const& data)
: buffer_()
{
::bzero( buffer_, sizeof buffer_);

void * p = buffer_;
header * h = reinterpret_cast< header * >( p);
::strncpy( h->name, "tcp", 3);
h->version = 1;
h->data_size = data.size();
char * p_ = buffer_;
p_ += 12; // <<== why 12 and not 9
::strncpy( p_, data.c_str(), h->data_size);
}

const std::string name() const
{
void const* p = buffer_;
header const* h = reinterpret_cast< header const* >( p);
return std::string( h->name, 3);
}

unsigned short version() const
{
void const* p = buffer_;
header const* h = reinterpret_cast< header const* >( p);
return h->version;
}

unsigned long data_size() const
{
void const* p = buffer_;
header const* h = reinterpret_cast< header const* >( p);
return h->data_size;
}

const std::string data() const
{
char const* p = buffer_;
p += 12; // <<== why 12 and not 9
return std::string( p, data_size() );
}

net::mutable_buffer as_mutable_buffer()
{ return net::make_mutable_buffer( buffer_); }

net::const_buffer as_const_buffer()
{ return net::make_const_buffer( buffer_); }
};
 
R

ralphmerridew

Hello,
I don't know why I've to increment the cahr pointer by 12 instead of 9 in
the code below.
regards, Oliver

Why are you manually counting up the data size? Why not change by
sizeof(header)?
 

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
473,994
Messages
2,570,223
Members
46,813
Latest member
lawrwtwinkle111

Latest Threads

Top