User
User

Reputation: 637

Array and Vector difference to use in programming

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.

Upvotes: 1

Views: 133

Answers (3)

James Kanze
James Kanze

Reputation: 153919

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

Upvotes: 2

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

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()

Upvotes: 0

jrok
jrok

Reputation: 55395

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

Upvotes: 4

Related Questions