Chris Batka
Chris Batka

Reputation: 143

c++ vector<char> and sockets

Is there a way to call send / recv passing in a vector ?

What would be a good practice to buffer socket data in c++ ? For ex: read until \r\n or until an upper_bound ( 4096 bytes )

Upvotes: 5

Views: 8546

Answers (3)

sbi
sbi

Reputation: 224149

std::vector<char> b(100); 
send(z,&b[0],b.size(),0);

Edit: I second Ben Hymers' and me22's comments. Also, see this answer for a generic implementation that doesn't try to access the first element in an empty vectors.

Upvotes: 10

me22
me22

Reputation: 641

One thing to watch out for: &v[0] is technically not allowed if the vector is empty, and some implementations will assert at you, so if you get buffers from others, be sure they're not empty before using this trick.

C++0x's vector has a .data() member function (like std::string's) to avoid this problem and make things clearer.

Upvotes: 6

Ben Hymers
Ben Hymers

Reputation: 26546

To expand on what sbi said, std::vector is guaranteed to have the same memory layout as a C-style array. So you can use &myVector[0], the address of the 0th element, as the address of the start of an array, and you can use myVector.size() elements of this array safely. Remember that those are both invalidated as soon as you next modify the vector though!

Upvotes: 6

Related Questions