I have a shared_ptr to an array of char, like this:
std::shared_ptr<char[]> tmp [ 10 ] ;
I have populated tmp, and now want to pass the data to execl(), which takes a char * const *. What's the right way to do it?
I have a shared_ptr to an array of char, like this:
std::shared_ptr<char[]> tmp [ 10 ] ;
I have populated tmp, and now want to pass the data to execl(), which takes a char * const *. What's the right way to do it?
I have a
shared_ptrto an array ofchar
What you have is a static array of 10 default-constructed std::shared_ptr objects. Is that what you really want?
Or do you need a single std::shared_ptr object that holds a pointer to a single array?
std::shared_ptr<char[]> tmp(new char[10]);
I have populated
tmp, and now want to pass the data toexecl(), which takes achar * const *.
No, it does not. It takes 2+ const char* parameters. Look at the declaration more carefully:
int execl(const char *path, const char *arg, ...);
There is a big difference between const char* and char * const *.
What's the right way to do it?
The std::shared_ptr<char[]>::get() method will return a char*, which can be passed to a const char* parameter.
Update: if you are trying to pass 10 seperate char[] arrays to execl(), one for each argument, then your static array is fine. Simply call tmp[index].get() for each argument you want to pass to execl():
std::shared_ptr<char[]> tmp[10];
// populate tmp, then ...
execl(file, tmp[0].get(), tmp[1].get(), ..., tmp[9].get());
Alternatively, use execv() instead:
std::shared_ptr<char[]> tmp[10];
// populate tmp, then ...
char* args[11];
for (int i = 0; i < 10; ++i)
args[i] = tmp[i].get();
args[10] = nullptr;
execv(file, args);
Which is especially useful if you don't know the number of arguments ahead of time:
std::vector<std::shared_ptr<char[]>> tmp;
// populate tmp, then ...
std::vector<char*> args;
for (auto &p : tmp)
args.push_back(p.get());
args.push_back(nullptr);
execv(file, args.data());