Sort of.
You can create something that (at least inside of the C++ domain) looks and acts like an array of pointers in one line. Since you haven't told us what you're hoping to accomplish by this, it's an open question whether it suits your purposes or not.
#include <vector>
#include <string>
#include <ranges>
int main() {
// some input to process
std::vector<std::string> input{ "A", "AB", "ABC"};
// do the transform in one line
auto ptrs = input | std::views::transform([](auto &s) { return s.c_str(); });
// use our "array of pointers":
for (auto i : ptrs)
printf("%s\n", i);
}
In theory, if you need something that's more like a real array of pointers (e.g., you can pass its address to a C function that expects the address of the beginning of an array) you can use a C++23 feature to do that:
auto ptrs = input | std::views::transform([](auto &s) { return s.c_str(); }) | to<std::vector>();
In this case, ptrs
will be an actual vector of pointers, so its .data()
will give you an actual pointer to a contiguous, dynamically allocated block of memory filled with pointers.
As I write this (6 June, 2023) there's only one compiler that actually implements that though: Microsoft C/C++ 19.34 (or, presumably newer). But g++ and Clang are still both missing this, so depending on your target, it may be no problem at all, or it may be completely unacceptable.
If you need to go the next step after that, and create a real, actual array...then you're largely out of luck. Although some compilers don't enforce the requirement, C++ requires that the size of an array be specified as a compile-time constant, so there's no way to create one with the same number of elements as an arbitrary vector (though if you know a maximum size at compile time, you can create an array of that maximum size and just use it).