modifying a vector (STL) in a function

C

clinisbut

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!!
}

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
}

It works good, but when I try to read some element with [] operator
doesn't works...
What's the correct way to deal with a vector inside a function???

PD: What's the diference between using & and * in function header's
parameter list?
 
Y

yaoyi

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 );
the char_array is empty!
you can use char_array.resize(11); instead
char_array[0] = 'A'; //<----No error compilation, but no
effect!!

}
 
J

jkherciueh

clinisbut said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top