上周我的课上有一个作业,我必须用空格、tabs和\n
作为分隔符来拆分一个字符串,并将每个“单词”存储在一个数组中。我想我已经很接近了,但是我的输出非常奇怪,所以如果有人能告诉我我忘记了什么,那就太好了。唯一的问题是我只能使用malloc
。
char **ft_split_whitespaces(char *str)
{
int i;
int j;
int k;
char **tab;
i = 0;
j = 0;
k = 0;
tab = (char**)malloc(sizeof(*tab) * (ft_nb_words(str) + 1));
while (str[i])
{
while (str[i] == ' ' || str[i] == '\t' || str[i] == '\n')
i++;
if (str[i])
{
if ((tab[j] = (char*)malloc(sizeof(char) * (ft_len_word(str + i) + 1))) == NULL)
return (NULL);
while (k < ft_len_word(str + i))
tab[j][k++] = str[i++];
tab[j++][k] = '\0';
k = 0;
}
}
tab[j] = NULL;
return (tab);
}
返回单词长度和单词数量的函数工作得很好,所以我认为问题来自于main函数。
发布于 2018-08-08 16:55:22
您的代码效率很低,因为您调用ft_len_word
的次数太多了,但是它似乎并没有脱离malloc
失败时的未定义行为。
问题可能出在您的ft_len_word
或ft_nb_words
版本中。你应该发布一个完整的程序来展示这个问题,以便进行适当的调查。
下面是一个不使用这些函数的修改版本:
#include <stdlib.h>
int ft_is_space(char c) {
return (c == ' ' || c == '\t' || c == '\n');
}
char **ft_split_whitespaces(const char *str) {
int i, j, k, len, in_space, nb_words;
char **tab;
nb_words = 0;
in_space = 1;
for (i = 0; str[i]; i++) {
if (ft_is_space(str[i]) {
in_space = 1;
} else {
nb_words += in_space;
in_space = 0;
}
}
tab = malloc(sizeof(*tab) * (nb_words + 1));
if (tab != NULL) {
i = 0;
j = 0;
while (str[i]) {
while (ft_is_space(str[i]))
i++;
if (str[i]) {
for (len = 1; str[i + len] && !ft_is_space(str[i + len]); len++)
continue;
if ((tab[j] = malloc(sizeof(*tab[j]) * (len + 1))) == NULL) {
while (j > 0)
free(tab[--j]);
free(tab);
return NULL;
}
for (k = 0; k < len; k++)
tab[j][k] = str[i + k];
tab[j++][len] = '\0';
i += len;
}
}
tab[j] = NULL;
}
return tab;
}
https://stackoverflow.com/questions/51740149
复制相似问题