Hameed
Hameed

Reputation: 11

convert const char ** to const char *

I have the following code in which works fine.

const char** array = new const char*[_list.size()];
unsigned index = 0;
for (std::list<std::string>::const_iterator it = _list.begin(); it != _list.end(); ++it) {
    array[index] = it->c_str(); 
    index++;
}

My question is, how can I convert const char ** to const char *. Please help.

Upvotes: -5

Views: 913

Answers (1)

Swift - Friday Pie
Swift - Friday Pie

Reputation: 14688

this is actually an XY question. Hameed should tell what problem he solves, not what step he got to finish to solve problem.What actually the task is? Convert list of strings to array of c strings? if yes, then should be done somewhat in this way ( sadly, one should copy data)

char** arr = new char*[_list.size()];
int i = 0;
for(auto it = _list.begin();  it != _list.end(); ++it, +i)
{
   const char *s = it->c_str(); // should not be modified or deleted
   const size_t l = strlen(s);
   arr[i] = new char [l+1];
   std::copy(&s[0],&s[l], &(arr[i][0]));
}

...

Do you need get i-th element from list?

auto it = _list.begin(); 
std::advance(it, i);
const char *a = it->c_str();

if doing that in loop for each element, just increment it instead.

concatenate all strings in one? iterate through list, calculate total length, then allocate array of char of that length and copy string one by one. i have vague memory that boost got this as algorithm::join already, but stl require long and frilly code, can't devise that on phone, whoever can edit answer is welcome. in different form that question with dozen solutions presents on stack: How to implode a vector of strings into a string (the elegant way)

Upvotes: -1

Related Questions