我正在尝试创建一个ft_split
函数应该:
使用 malloc 分配并返回通过使用字符 'c' 分割 's' 获得的字符串数组
作为分隔符。该数组必须以 NULL 指针结尾。
我已将所有代码包含在下面的代码示例中,以及调试器给出错误之一的断点。
现在遇到以下问题:
- 当我输入一个字符串并在其末尾添加分隔符时,它会出现此错误
字符串:
“存在还是不存在,这是一个问题”
错误:
分段故障
- 当我输入这个字符串时
字符串:
“你好呀”
它会给出正确的答案,然后出现此错误
Hello
there
分段故障
- 我只是不知道如何释放创建的内存分配,我已经包含了我认为正确的评论方式。
my code:
size_t ft_strlen(const char *s)
{
size_t i;
i = 0;
while (s[i] != '\0')
{
i++;
}
return (i);
}
char *ft_strcpy(char *dest, const char *src)
{
int i;
i = 0;
while (src[i] != '\0')
{
dest[i] = src[i];
i++;
}
dest[i] = '\0';
return (dest);
}
char *string_length(char const *str, char c, int i)
{
int j;
char *string;
j = 0;
// when i try the debugger with the first string in the main function it goes
// directly to this line and break.
string = (char *)malloc((ft_strlen(str)) * sizeof(*string));
if(!string)
return (NULL);
while (str[i] == c)
i++;
while (str[i])
{
*string = str[i];
if (str[i + 1] == c || str[i + 1] == '\0')
{
string++;
j++;
*string = '\0';
return (string - j);
}
string++;
j++;
i++;
}
return (0);
}
int count_strings(char const *str, char c)
{
int i;
int count;
int def;
i = 0;
count = 0;
def = 1;
while (str[i] == c)
i++;
while (str[i])
{
if (str[i] == c && def == 1)
{
i++;
def = 0;
}
if (str[i] != c && def == 0)
{
count++;
def = 1;
}
i++;
}
return (count);
}
int first_del(char const *str, char c, int i)
{
while (str[i] == c)
i++;
return (i);
}
char **ft_split(char const *s, char c)
{
int count;
int i;
int len;
int num_of_strings;
char **split;
char *string;
char **it;
i = 0;
count = 0;
num_of_strings = count_strings(s, c);
split = (char **)malloc((num_of_strings + 1) * sizeof(char *));
if (!split)
return (NULL);
split[num_of_strings + 1] = NULL;
while (i <= num_of_strings)
{
count = first_del(s, c, count);
string = string_length(s, c, count);
len = ft_strlen(string);
split[i] = (char *)malloc(len + 1);
ft_strcpy(split[i], string);
count += len;
i++;
free(string);
string = NULL;
}
return (split);
}
int main(void)
{
char s[] = " To be or not to be that is the question ";
char **split_strings = ft_split(s, ' ');
for (int i = 0; i < 10; i++)
printf("%s\n", split_strings[i]);
char s2[] = "Hello there";
char **split_strings2 = ft_split(s2, ' ');
for (int i = 0; i < 2; i++)
printf("%s\n", split_strings2[i]);
}
string = (char *)malloc((ft_strlen(str) + 1) * sizeof(*string));
split = (char **)malloc((num_of_strings + 2) * sizeof(char *));
释放主函数中的内存分配:
int i = 0;
while (split_strings && split_strings[i])
{
free (split_strings[i]);
i++;
}
free (split_strings);
归功于 xing
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)