Reputation: 21
How can we pass vector
variables to a function? I have a vector
of char*
and a function which will take a char *
as an argument. How can I pass the vector
variable to this function?
Upvotes: 0
Views: 2667
Reputation: 106068
If you have a function taking a char* argument, then you can only pass one of the char* in the vector. For example:
std::vector<char*> v;
char buf[] = "hello world";
v.push_back(buf);
the_function(v[0]);
If you want to call the function on each member in the vector, just loop:
for (std::vector<char*>::iterator i = v.begin(); i != v.end(); ++i)
the_function(*i);
EDIT: based on your comment below, you actually want to write a function that accepts the vector as an argument... try:
void the_function(const std::vector<char*>& v)
{
// can access v in here, e.g. to print...
std::cout << "[ (" << v.size() << ") ";
for (std::vector<char*>::iterator i = v.begin(); i != v.end(); ++i)
std::cout << *i << ' ';
std::cout << " ]";
}
If you have an existing function that you want to call, and you don't want to change its argument list...
void TV_ttf_add_row(const char*, const char*, const void*);
...then, say you know the vector will have enough elements:
assert(v.size() >= 3); // optional check...
TV_ttf_add_row(v[0], v[1], v[2]);
or
if (v.size() >= 3)
TV_ttf_add_row(v[0], v[1], v[2]);
or, if you want an exception thrown if there aren't enough elements in v
, then...
try
{
TV_ttf_add_row(v.at(0), v.at(1), v.at(2));
}
catch (const std::exception& e)
{
std::cerr << "caught exception: " << e.what() << '\n';
}
(the try/catch block doesn't have to surround the single function call - just as long as the v.at( )
calls are somewhere inside the try
block or a function directly or indirectly called from inside the block).
Upvotes: 3
Reputation: 231063
If you need to pass the contents of a std::vector to a function that takes a C array, you can take the address of the first element of the vector:
void someCfunc(char *);
std::vector<char *> somevec;
// set up the vector ... then:
someCfunc(&somevec[0]);
HOWEVER - be careful you don't get the C string convention mixed up here! A std::vector
will not append a '\0'
to the end of the string automatically; you must do that manually. If it's just a byte buffer, you'll need to pass the vector's size separately. And if you're receiving data back into the vector, the C function cannot expand the vector on its own, so it's up to you to ensure the vector is large enough beforehand.
Note also that this applies only to std::vector
and not to other STL containers.
Upvotes: 0
Reputation: 27164
You can also access the vector elements using its index:
void f(char* s)
{
// do something with s
}
std::vector<char*> char_vect;
size_t len = char_vect.size();
for (size_t i=0; i<len; ++i)
f(char_vect[i]);
Upvotes: 0