2012-03-12 2 views

답변

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

첫 번째'for' 루프의 내용이 잘못된 유형을 할당하고 문자열이 널로 끝나지 않습니다 ('strncpy()'를 사용하지 마십시오). 'array [index] = new char [it-> size() + 1];을 시도해보십시오. memcpy (배열 [인덱스], it-> c_str(), it-> size() + 1);'. 대신'strdup()'를 사용하는 것이 더 나을 수도 있습니다. –

+0

의견을 보내 주셔서 감사합니다. 제 실수를 고쳤다 고 생각합니다. –

관련 문제