我必须将每个单词与字符串分开,并且每个单词必须在矩阵中排成一行。一个单词由空格,制表符,换行符分隔,然后程序打印每一行。矩阵的末尾用0标记。
#include<stdio.h>
#include<stdlib.h>
char *ft_strdups(char *str, int start, int to)
{
char *p;
int i;
i = 0;
if (to < start)
return (NULL);
p = (char*) malloc(sizeof(char)*(to - start + 1));
if (!p)
return (NULL);
while(start < to && str[start])
{
p[i] = str[start];
start++;
i++;
}
p[i] = '\0';
return (p); // This function dynamicaly allocates the string
}
int tw(char *str)
{
int i;
i = 0;
while (str[i] != '\t' && str[i] != '\n' && str[i] != ' ' && str[i])
i++;
return (i); // This function traverses the word and returns the length
}
int nb_words(char *str) // counts the numbers of words
{
int i;
int k;
k = 0;
while (str[i] != '\0')
{
if(str[i] != '\t' && str[i] != '\n' && str[i] != ' ' && str[i])
{
i = i + tw(str + i);
k++;
}
else
i++;
}
return (k);
}
char **ft_split_whitespaces(char *str)
{
int i;
char **p;
int j;
j = 0;
i = 0;
p = (char**)malloc(sizeof(char) * (nb_words(str) + 1));
while(str[i] != '\0')
{
if (str[i] != '\n' && str[i] != '\t' && str[i] != ' ')
{
p[j] = ft_strdups(str, i, i + tw(str + i));;
j++; // here is the allocation
i = tw(str + i) + i;
}
else
i++;
}
p[j] = 0;
return (p);
}
int main(int ac, char **av)
{
char **p;
int i;
i = 0;
if(ac != 2)
return(0);
p = ft_split_whitespaces(av[1]);
while (p[i])
{
printf("%s\n",p[i]);
i++;
}
}
问题在于,如果我给出一个超过16个单词的字符串(例如:./a.out "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20"
),它会崩溃,从而导致打印一些非ascii字符而不是我之前的单词。