我正在尝试分离用''填充的字符串,并将其存储在数组中。为此,我编写了代码,

string* componentsOfStringSeperatedBystring(string originalString, string stringCompare){

string *arryOfStrings=NULL;

string *tempArrayString = NULL;
for (int i=0; i<originalString.length(); i++) {


    size_t position = originalString.find(stringCompare);
    cout << "\nposition" <<position;

    if (position == originalString.npos) {

        break;
    }
    size_t subStringLength = originalString.length() - position;

    cout << "\nsubStringLength" <<subStringLength;
    string subString = originalString.substr(0,position);

    cout << "\nsubString" <<subString;

    tempArrayString = (string*)realloc(arryOfStrings, (i+1)*sizeof(string));

    cout << "\n i \t" <<i;
    if (tempArrayString != NULL) {

        arryOfStrings = tempArrayString;
        arryOfStrings[i] = subString;
    }


    cout << "\narryOfStrings" <<arryOfStrings;
    originalString = originalString.substr(position+1,subStringLength);
}

return arryOfStrings;
}

我在“arryOfStrings [i] = subString;”行上崩溃了,如果我只简单地先分配足够的空间,然后不重新分配,就不会崩溃。

最佳答案

不要在C++风格的对象上使用C风格的内存管理。完全采用C样式(使用以空值结尾的char*字符串)或完全采用C++样式(使用std::vector<std::string>)。

10-06 15:08