Reputation: 4869
C++ newbie.
I have following class and its argument is char*
,
How do I copy that to member variable char*
?
After that I need to know the size of array ?
class TestParam {
public:
char*[] arr;
TestParam (const char* Pre, char* Post[]){
arr = Post;
}
};
....
TestParam testParam[1] = { TestParam ("aa", (char*[]){"bb","cc","dd"})};
I know about std::string but I had to use char*
because I am initializing the object like above in my code. Is it possible by std::string ?
Upvotes: 0
Views: 867
Reputation:
#include <iostream>
#include <vector>
class TestParam {
public:
template <std::size_t N>
TestParam(const char* pre, const char* (&arr_ref)[N]) {
arr.reserve(N);
for(const char* p: arr_ref) {
if(p) arr.push_back(std::string(p));
}
}
std::vector<std::string> arr;
};
int main() {
const char* a[] = { "Hello", " " , "World" };
TestParam param((char*)0, a);
for(const std::string& s: param.arr) std::cout << s;
std::cout << std::endl;
return 0;
}
Upvotes: 0
Reputation: 409196
I would suggest a solution where you use std::string
and std::vector
instead, like this:
class TestParam {
public:
std::vector<std::string> arr;
TestParam (const std::string& Pre, const std::vector<std::string>& Post){
arr = Post;
}
};
...
TestParam testParam[1] = { TestParam ("aa", {"bb","cc","dd"})};
Upvotes: 1
Reputation: 67743
You first need the number of elements in Post
- that needs to be passed in as another argument, unless Post
is defined to have a NULL last element, in which case you need to count the non-NULL elements first.
Once you know that, you can allocate memory for arr
.
Finally, you can either perform a shallow copy by assigning the pointer values (eg. arr[i] = Post[i]
, or a deep copy by duplicating each string. You haven't told us which you need.
Upvotes: 0
Reputation: 206546
You need to allocate sufficient memory to the destination pointer and then use std::copy
.
Tip: Consider using std::string
instead.
Upvotes: 2