Issue
So I want to pass arguments to following function
execve(char *filename, char *argv[], char *envp[])
currently my argv[]
is a string array. I want to convert it into a char* array
so I can pass it to this function.
I have looked around and found many ways to convert a string to a char
array but how to convert a string array to an array of char array I guess would be the right term
Any help?
Solution
You'll need to get the address of the data inside your std::string
s. Note, that these are not required to be null-terminated, i.e., you'll need to make sure that all strings are null terminated. Also, the array passed as argv
also needs to have the last element to be a null pointer. You could use code along the lines of this:
std::string array[] = { "s1", "s2" };
std::vector<char*> vec;
std::transform(std::begin(array), std::end(array),
std::back_inserter(vec),
[](std::string& s){ s.push_back(0); return &s[0]; });
vec.push_back(nullptr);
char** carray = vec.data();
When compiling with C++03, there are some changes necessary:
- Instead of using the lambda expression, you need to create a suitable function or function object doing the same transformation.
- Instead of using
nullptr
you need to use0
. - In C++03
std::string
is not guaranteed to be contiguous, i.e., you need an additional, auxiliarystd::vector<char>
to hold a contiguous sequence of characters. There are no functions
begin()
andend()
deducing the size of an array but they can easily be implemented in C++03:template <typename T, int Size> T* begin(T (&array)[Size]) { return array; } template <typename T, int Size> T* end(T (&array)[Size]) { return array + Size; }
The C++03
std::vector<T>
doesn't have adata()
member, i.e., you also need to take the address of the first element.
Answered By - Dietmar Kühl Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.