【发布时间】:2021-05-16 12:34:24
【问题描述】:
我目前正在学习指针和malloc 函数的工作原理。
我正在尝试用 C 语言编写一个将字符串作为参数的函数。基本上,它将这个字符串的每个单词存储在char **ptr 中,并且在找到空格/制表/'\n' 字符时会区分单词。
例如,字符串“hello world”将存储为ptr[0] = "hello、ptr[1] = world。
到目前为止,这是我写的:
#include "libft.h"
#include <stdlib.h>
char **ft_split_whitespaces(char *str)
{
int i;
int j;
int k;
char **tab;
i = 0;
j = 0;
k = 0;
tab = (char **)malloc(sizeof(char) * 8);
*tab = (char *)malloc(sizeof(char) * 8);
while(str[i])
{
k = 0;
while(str[i] == 9 || str[i] == 32 || str[i] == 10 || str[i] == '\0') // if a whitespace or a tabulation or a '\n' char is found, we go further in the string and do nothing
{
i++;
}
while(str[i] != 9 && str[i] != 32 && str[i] != 10 && str[i] != '\0') // if this isn't the case, we put the current char str[i] in the new array
{
tab[j][k] = str[i];
k++;
i++;
}
if(str[i] == 9 || str[i] == 32 || str[i] == 10 || str[i] == '\0') // now if a new whitespace is found we're going to store the next word in tab[j+1]
{
j++;
}
i++;
}
return (tab);
}
int main(void)
{
char str[] = " hi im a new bie learning malloc\nusage";
ft_split_whitespaces(str);
}
请注意,我尝试 malloc 几个值,但它似乎没有改变任何东西:当尝试将单词“im”(第二个单词)的字符“i”复制到我的数组中时,它会出现段错误。
你们能指导我并告诉我我错过了什么吗?
提前非常感谢!
【问题讨论】:
-
使用
isspace()而不是与数字比较。
标签: c pointers segmentation-fault malloc