我正在尝试分离用 ' ' 填充的字符串并将其存储在数组中。为此,我编写了代码,
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;”行上崩溃了,如果我只是先分配足够的空间,然后不重新分配,我就不会崩溃。