how can i pass an element of vector<char*> to a function which takes an argument of char* ?
Printable View
how can i pass an element of vector<char*> to a function which takes an argument of char* ?
Here's one quick, simple and very ugly example:
Code:#include <iostream>
#include <vector>
using namespace std;
void foo(char* s)
{
cout<<s;
}
int main( )
{
char* t1 = "Test1";
char* t2 = "Test2";
vector<char*> v;
v.push_back(t1);
v.push_back(t2);
foo(v[0]);
return 0;
}
- Micko
that's what i tried to do, but it's not working, take a look here:
Code:void func(vector<char*>* vec)
{
char str[256];
//then i put some text in str
vec->push_back(str);
foo(vec[0]);
}
func(&vector);
Note that in function func, vec is a pointer to a vector, not the actual vector. When you use the [] operator on the pointer, the compiler is assuming that you mean to do pointer addition. When you're calling foo, you're actually calling it with the vector object.
You can fix this problem a few different ways.However, you don't really need a pointer in this function. A reference would make this much nicer.Code:Solution 1
//Dereference the vector pointer, and then apply the [] operator
void func(vector<char*>* vec)
{
//snip
foo((*vec)[0]); //Ugly, but it works.
}
Code:Solution 2
//Use a reference to the object
void func(vector<char*> &vec)
{
//snip
vec.push_back(str); //Use dot operator; no pointer
foo(vec[0]); //Works like you'd think
}
//To call
func(vector); //Pass the object, not the address
Why are you using a pointer to a vector?
The problem you are having is that the vector contains the pointer to the array's data. It doesn't contain the data itself.
Instead of using vector<char*> you might want to use a vector<std::string> instead
just to be sure:
when i use a reference to the vector, there is no copy of the vector? it working with the original vector?
yep.
Don't overlook Thantos's point, though. When you save that char* in the vector, remember that it will go out of scope once the function returns. You really should be using std::string instead.
ok thanks all
Also don't forget that a proper compiler should reject
char *p = "Bla";
String literals should only ever be assigned to const char *, because usually they're immutable.
Is that true? I thought that was allowed for backwards compatibility with C?Quote:
Originally Posted by CornedBee
technically it should reject it because it ignoring the const-ness of it. Though I have yet to use one that does.
The standard allows it, but it is deprecated.
It should not be rejected, but a warning would be appropriate, and you shouldn't be using it.
Well, give GCC or MSVC the right compiler switches and they will reject it.