2012-03-12 11 views
-1

可能性の重複:
Converting a std::list to char*[size]リスト<string>をchar **に変換するにはどうすればよいですか?

どのように私は** charへの文字列、リストのリストを変換することができますか? 利用可能なSTLメンバーメソッドを使用する方法はありません。そうでない場合は、どのように達成できますか?

私は、送信する文字列のリストを持つC++から入力をchar **として受け取るC関数を呼び出しています。

答えて

1

残念ながら、リスト内の要素はメモリ内で連続していないため、リストを配列に直接変換する方法はありません。だからあなたの方法は、新しい配列を割り当てて、文字列をコピーすることです。 、あなたを

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

    // use the array 


delete [] array; 
} 

リストを変更することができたり、constの配列から別の何かが必要な場合:あなただけのconst char配列をしたいとあなたはconstのchar配列を使用しながら、リストは変更されません場合は、次の操作を行うことができます文字列をコピーする必要があります:

void UseListOfString(const std::list<std::string>& l) { 
    unsigned list_size = l.size(); 
    char** array = new char*[list_size]; 
    unsigned index = 0; 
    for (std::list<std::string>::const_iterator it = l.begin(); it != l.end(); ++it) { 
    array[index] = new char[it->size() + 1]; 
    memcpy(array[index], it->c_str(), it->size()); 
    array[it->size()] = 0; 
    } 

    // use the array 

    for (unsigned index = 0; index < list_size; ++index) { 
    delete [] array[index]; 
    } 
    delete [] array; 
} 

この回答が役立ちます。

+2

2番目の例には少なくとも2つのバグがあります:最初の 'for'ループの内容は間違った型を割り当て、文字列はヌルで終了しません(' strncpy() 'は避けてください)。 'array [index] = new char [it-> size()+ 1];を試してください。 memcpy(配列[インデックス]、it-> c_str()、it-> size()+ 1); '代わりに 'strdup()'を使う方が良いでしょう。 –

+0

あなたのコメントをありがとう、私は私のエラーを修正したと思う。 –

関連する問題