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