我试图编程一个拆分,它需要一个字符数组与多个单词并将每个单词分隔成自己的较小的字符数组。所有较小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