5

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 )

Chris Batka
  • 143
  • 1
  • 4
  • You mean you want to pass the entire data structure as is? – Alex Sep 09 '09 at 14:12
  • 1
    instead of: char b[100]; send(z,b,100,0); i would like to send a vector. i may have found the answer in a different thread http://stackoverflow.com/questions/550797/is-there-a-better-way-to-print-a-string-with-cout-up-to-n-characters is that a good practice though? – Chris Batka Sep 09 '09 at 14:14
  • 1
    Using the adress of the first element is fine. So you can use it for a send(). The standard guarantees that all elements are in contiguous memory. The reverse will not work though because you may not have the correct size. – Martin York Sep 09 '09 at 15:48

3 Answers3

10
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.

Community
  • 1
  • 1
sbi
  • 219,715
  • 46
  • 258
  • 445
6

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!

Ben Hymers
  • 25,586
  • 16
  • 59
  • 84
  • 3
    To clarify what Ben said, it's invalidated as soon as you modify the vector itself, not the contents of the vector. In other words, if you cause the vector to reallocate its contents, the address you got back from &v[0] is invalid. – moswald Sep 09 '09 at 14:40
  • 1
    I wouldn't say "same memory layout", since sizeof(vector) is a constant, but rather state the actual guarantee of continuity: For all T != bool, vector v, i in [0, v.size()), you know that &v[i] == &v[0] + i. – me22 Sep 12 '09 at 15:07
6

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.

me22
  • 651
  • 3
  • 8