By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,847 Members | 2,206 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,847 IT Pros & Developers. It's quick & easy.

problem with pointer arithmetic

P: n/a
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_); }
};

Feb 23 '07 #1
Share this Question
Share on Google+
3 Replies


P: n/a
Oliver Kowalke wrote:
Hello,
I don't know why I've to increment the cahr pointer by 12 instead of 9 in
the code below.
Search the archive for "padding bytes"

--
Ian Collins.
Feb 23 '07 #2

P: n/a
On Feb 23, 1:20 pm, Oliver Kowalke <oliver.kowa...@gmx.dewrote:
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)?

Feb 23 '07 #3

P: n/a

Oliver Kowalke wrote:
>
message()
: buffer_()
You can do not call default constructor "buffer_()" explicitly.
{ ::bzero( buffer_, sizeof buffer_); }
If you just want to terminate asciiz string, then instead of non-standard
"bzero" you can write "buffer_[0]=0;"

--
Maksim A. Polyanin
http://grizlyk1.narod.ru/cpp_new

"In thi world of fairy tales rolls are liked olso"
/Gnume/
Feb 24 '07 #4

This discussion thread is closed

Replies have been disabled for this discussion.