user229160
user229160

Reputation:

Initializing a public char buffer dynamically

I am a noob to C++. I have a question regarding initialization of a character buffer dynamically

class Pkg {
  public:
    Header t;
    char buf[LENGTH];
};

I am going to send the object of the class over the network. Header class is converted to network byte order

So, I want to send it like this

Pkg ackpkt;

sendto(sd, &ackpkt, sizeof(ackpkt), 0,(struct sockaddr*)socket1,sizeof(struct sockaddr_in);

The LENGTH field here should be dynamically assigned each time just before I call sendto. One way I think of doing this is by declaring LENGTH to be global.

At the receivers side, I want to receive the object in an object of the same class.i.e the data of object t should be organized in ackpktrecv.t and buffer in ackpktrecv.buf

recvfrom(sd, &ackpktrecv, sizeof ackpktrecv, 0, (struct sockaddr*)&sockaddrs, &len);

How can I receive the object with the character buffer having the same length as LENGTH Can anybody suggest me in what way I can achieve this ?

Upvotes: 1

Views: 256

Answers (2)

JSBձոգչ
JSBձոգչ

Reputation: 41378

I recommend an RAII idiom:

  • Make the constructor for Pkg take a length parameter, and allocate buf in the constructor with new char[length].
  • Make the destructor for Pkg do delete[] buf

Then every time through the loop, you simply create a new Pkg object with the desired length.

Upvotes: 0

JaredPar
JaredPar

Reputation: 754565

Since this is C++, consider use a vector<T> instead of a char.

class Pkg {
public:
  Pkg(vector<char>::size_type size) :buf(size) {
  }

  vector<char> buf;
};

That allows you to send data in the following way

Pkg ackpkt(someSize);
sendto(
  sd,  
  &(ackpkt.buf[0]), 
  actpkt.buf.size(), 
  0,
  (struct sockaddr*)socket1,
  sizeof(struct sockaddr_in)

Upvotes: 1

Related Questions