clinisbut wrote:
I'm trying to understand what's wrong with this:
void getAllData( std::vector<unsigned char> &char_array )
{
char_array.clear();
char_array.reserve( 11 );
char_array[0] = 'A'; //<----No error compilation, but no effect!!
Actually, you have an out-of-bounds error and the code has undefined
behavior.
}
and then I call this function:
std::vector<unsigned char> char_array;
getAllData( char_array );
But if I do this:
void getAllData( std::vector<unsigned char> &char_array )
{
char_array.clear();
char_array.reserve( 11 );
char_array.push_back('A'); //Works
}
This is a correct way to fill a vector.
It works good, but when I try to read some element with [] operator
doesn't works...
operator[] and the at() function only allow you to access vector elements
that are already stored in the container; calling them will not magically
enlarge the vector (as opposed to std::map, where this kind of magic
happens). Thus, you have to populate the vector _before_ you can access its
elements. The push_back() function is the way to go.
What's the correct way to deal with a vector inside a function???
That all of this happens inside a function is immaterial.
PD: What's the diference between using & and * in function header's
parameter list?
& denotes a reference parameter and * denotes a pointer.
Best
Kai-Uwe Bux
.