我正在嘗試編寫一個函數,它將一個字符串和一個分隔符作爲輸入並返回一個字符串數組。出於某種原因,下面的代碼運行到分段錯誤。我想知道可能是什麼問題?在C++中分割函數
char** split(string thing, char delimiter){
thing+='\0';//add null to signal end of string
char**split_string = new char*[100];
int i=0,j=0,l=0; //indexes- i is the ith letter in the string
// j is the jth letter in the lth string of the new array
int length = thing.length();
while (i < length){
if ((thing[i]!=delimiter && thing[i]!='\0')){
split_string[l][j]=thing[i];
j++;
}
else {
j=0; //reset j-value
l++;
}
i++;
}
return split_string;
}
爲什麼不將源字符串「拆分」爲字符串向量?爲什麼要使用指針和動態分配(特別是如果源字符串中沒有100個「標記」)? –
'split_string [l]'是一個未初始化的指針,包含一些隨機垃圾,指向內存中的某個隨機位置。 'split_string [l] [j] = thing [i]'然後嘗試寫入該隨機存儲單元。 –
您是否嘗試過使用Google錯誤消息?瞭解它究竟意味着什麼?然後,很容易找到你出錯的地方。 –