0

The API expects an array of zero-terminated c-strings (char*). The array itself is to be terminated with a null pointer (nullptr).

4
  • Can you please add the APIs in your question? What do you mean by The array itself is to be terminated with a null pointer (nullptr).? Can you elaborate that? Commented Mar 7, 2020 at 5:22
  • 1
    @Azeem An array of C-style strings is an array of char*. Each of these char* will point to a null-terminated string except the last entry in the array. The last entry in the array is nullptr so that the size of the array does not need to be passed around. (I've seen this interface before, but I forget where.) Commented Mar 7, 2020 at 5:25
  • @JaMiT: Got it, thanks! :) Commented Mar 7, 2020 at 5:31
  • @Azeem I'm using the exec function family in posix. Functions of the exec family that require such arrays as arguments have v or e in their name. Commented Mar 7, 2020 at 6:08

1 Answer 1

0

How about using std::transform?

#include <iostream> #include <string> #include <vector> #include <algorithm> int main() { std::vector<std::string> v = {"asd","qwe"}; const char** c = new const char*[v.size()]; std::transform(v.begin(), v.end(), c, [](const std::string& s) { return s.c_str(); }); for (size_t i=0;i<v.size();i++) { std::cout << c[i] << std::endl; } delete[] c; return 0; } 

But do mind that the array(here c) should be in the same scope as the vector(here v) or the vector should not get destroyed before the use of the array(c) is over.

If you want a char** instead and not const char**, you can use .data() instead of .c_str()

Sign up to request clarification or add additional context in comments.

4 Comments

You don't have to allocate the array manually. I'd use std::vector<const char *> s;.
@HolyBlackCat and then use s.data() to access the underlying data?
@theWiseBrо Yep.
@@theWiseBrо @HolyBlackCat Yeah, using new and delete directly is sloppy C++.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.