Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constant character pointer using unique_ptr

Let's say that I have a vector<string> input and I need to pass this to a function that takes a const char** argument. My thought had been to use a unique_ptr like this:

const auto output = make_unique<char*>(size(input));

But I can't seem to turn a const unique_ptr<const*> into a const char**. Is there a way to accomplish this, or perhaps a simpler alternative?

like image 638
Jonathan Mee Avatar asked Jan 27 '23 18:01

Jonathan Mee


1 Answers

I would just build a vector of pointers to the c_str()'s of the strings and then get a pointer to that.

std:vector<const char*> pointers;
pointers.reserve(input.size());
for (const auto& e : input)
    pointers.push_back(e.c_str()); // get const char *'s
auto argument = pointers.data(); // get pointer to const char*'s - const char**

Or using a unique_ptr

auto pointers = std::make_unique<const char*[]>(size(input))
for (size_t i = 0; i < input.size(); ++i)
    pointers[i]= input[i].c_str(); // get const char *'s
auto argument = pointers.get(); // get pointer to const char*'s - const char**
like image 124
NathanOliver Avatar answered Jan 30 '23 14:01

NathanOliver