1

I have one problem to use std::vector instead of std::array. Most people says they serve for same purpose except their way of memory allocation (array allocates memory statically for its elements and vector allocates memory dynamically ). To clear my understanding I tried something but failed.

I had my running code using array was working fine.

char userInput[MAX_DATA] = { '\0' }; 
std::cout<<"\enter some char: ";
std::cin.getline(userInput, MAX_DATA);
int bytes_sent = send(socketFD, userInput, strlen(userInput), 0);
//send function definition send(__in SOCKET s, __in_bcount(len) const char FAR * buf, __in int len, __in int flags);

By using vector I have changed my code lines by instead of above defined code:

std::vector<char> userbuffer;
std::cout<<"\enter some char: ";
cin>>input;// i only want to send only the data i entered here in run time.
int bytes_sent = send(socketFD, userbuffer, userbuffer.size(), 0);
//error C2664: 'send' : cannot convert parameter 2 from 'std::vector<_Ty>' to 'const char* '

I am really new to c++ STL concepts. Can someone please help me find out what I am doing wrong? My intention to do this is to see dynamic memory allocation.

3 Answers 3

4

(I assume send_to takes a char* for 2nd parameter)

std::vector encapsulates a dynamically resizable array. You can get a pointer to the element type taking address of the first element:

&userbuffer[0]

or, since C++11, by calling member function data:

userbuffer.data()

This is guaranteed to work because the internal array is stored contiguously.

Sign up to request clarification or add additional context in comments.

Comments

2

In addition to what jrok said: there is no operator>> to input into an std::vector<char>. To come closest to what you originally wrote:

std::string userInput;
std::cout << "enter some char: ";
if ( !std::getline( std::cin, userInput ) ) {
    //  Error...
}
int bytesSent = send( socketFG, userInput.data(), userInput.size(), 0 );

(You forgot to check for an error in your initial version as well.)

2 Comments

Thank you ! I faced a run time error because of that but have fixed that:)
And in first version i am using if(std::cin.fail()), so that worked fine, i just had problem in second version.
0

It is better to use class std::string instead of std::vector in this case. You can pass an object of type std::string to the function calling member function c_str()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.