我試圖編程一個拆分,它需要一個字符數組與多個單詞並將每個單詞分隔成自己的較小的字符數組。所有較小char數組的指針都保存在一個指針數組中,因此我可以返回一個雙指針。C - 拆分減慢我的電腦
你可以看看我的代碼,看看你是否看到任何錯誤。當我嘗試運行我的程序時,我的電腦逐漸變慢,3-4秒後我無法移動我的鼠標或alt + f4我的編輯器。所以有些事情必須嚴重錯誤!
另外我完全不熟悉C編程,所以我肯定會在那裏犯一個愚蠢的錯誤。
char **split(char *s) {
char **result;
int wrd_cnt = 2; //I'm adding NULL at the end of the pointer-array.
//Counts the number of words to allocate memory for the pointer-array.
for(int i = 0; i < strlen(s); i++) {
if(s[i] == ' ') {
wrd_cnt++;
}
}
result = malloc(wrd_cnt * sizeof(char*));
//Counts letters in each word to allocate memory for every single small char-array with malloc.
for(int i = 0; i < strlen(s); i++) {
for(int j = 0; j < (wrd_cnt); j++) {
int char_cnt = 0;
for(int k = 0; s[i] != ' ' || s[i] != '\0'; k++, i++) {
char_cnt++;
result[j] = malloc(char_cnt * sizeof(char));
}
}
}
//Puts each word into their own place in the pointer array.
for(int i = 0; i < strlen(s); i++) {
for(int j = 0; j < (wrd_cnt); j++) {
for(int k = 0; s[i] != ' ' || s[i] != '\0'; k++, i++) {
result[j][k] = s[i];
}
}
}
result[wrd_cnt-1] = NULL;
return result;
}
's [i]!=''|| s [i]!='\ 0''應該是's [i]!=''&& s [i]!='\ 0'',否則你會超出字符串邊界。 –
\ t和\ v應該被認爲是 – rak007
@AndreaBiondo這不是說s [i]的條件是''和'\ 0'滿足條件嗎?這是不可能的? – Magnarok