我目前正在学习指针和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] == ' ') // 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] != ' ') // 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] == ' ') // 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 mallocnusage";
ft_split_whitespaces(str);
}
请注意,我已经尝试malloc几个值,但它似乎没有改变任何东西:当试图将字符' I'的'im'(第二个单词)复制到我的数组中时,它会出现分段错误。
你们能指导我,告诉我我错过了什么吗?
提前感谢!
这一行:
tab = (char **)malloc(sizeof(char) * 8);
只分配8个字节来存储所有的指针。假设8是指针的最大数目,它应该是:
tab = (char **)malloc(sizeof(char *) * 8);
这条线:
*tab = (char *)malloc(sizeof(char) * 8);
为第一个单词分配空间,最多可为7个字符长加上一个空结束符。
然而,这只为tab[0]
所指向的第一个字分配内存。该代码不为剩余的单词分配任何内存。
ft_split_whitespaces
应该如何表示它从输入中分离出来的单词数?一种方法是在指向列表中最后一个单词的指针后面添加一个空指针。
下面是一个工作演示。它使用strspn
和strcspn
函数来遍历输入字符串的空白和非空白部分。它扫描输入字符串两次——一次确定单词的数量,一次分配和复制单词。它为以空结束的指针列表分配一个内存块,并为每个单词分配一个内存块。
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
/* Free NULL-terminated list of strings. */
void ft_free_strlist(char **strings)
{
if (strings)
{
char **ss = strings;
while (*ss)
{
free(*ss++);
}
free(strings);
}
}
char **ft_split_whitespaces(const char *input)
{
static const char white[] = "tnvfr ";
size_t nwords;
size_t i;
size_t wordlen;
char **words;
const char *s;
/* Determine number of words in input string. */
nwords = 0;
s = input;
s += strspn(s, white); /* Skip initial whitespace. */
while (*s)
{
/* Found non-whitespace at beginning of word. */
nwords++;
s += strcspn(s, white); /* Skip non-whitespace. */
s += strspn(s, white); /* Skip whitespace. */
}
/* Allocate memory for NULL-terminated list of words. */
words = malloc((nwords + 1) * sizeof(words[0]));
if (words != NULL)
{
/* Rescan input, allocate and copy words. */
s = input;
for (i = 0; i < nwords; i++)
{
s += strspn(s, white); /* Skip whitespace. */
wordlen = strcspn(s, white); /* Determine word length. */
/* Allocate memory for null-terminated word. */
words[i] = malloc((wordlen + 1) * sizeof(*s));
if (words[i] == NULL)
{
/* Error will be dealt with later. */
break;
}
/* Copy word (source is not null-terminated). */
memcpy(words[i], s, wordlen * sizeof(*s));
words[i][wordlen] = 0; /* Append null terminator to word. */
s += wordlen; /* Skip past the copied word. */
}
/* NULL-terminate the list of words. */
words[i] = NULL;
if (i < nwords)
{
/* Could not allocate enough memory. Free what we got. */
ft_free_strlist(words);
words = NULL; /* Will return NULL later. */
}
}
if (words == NULL)
{
/* There was a memory allocation error. */
errno = ENOMEM;
}
/* Return the NULL-terminated list of words, or NULL on error. */
return words;
}
/* Print NULL-terminated list of strings. */
void ft_print_strlist_const(const char *const *strings)
{
if (strings)
{
while (*strings)
{
puts(*strings);
strings++;
}
}
}
void ft_print_strlist(char *const *strings)
{
ft_print_strlist_const((const char *const *)strings);
}
int main(void)
{
static const char str[] = " hi im a new bie learning mallocnusage";
char **words;
words = ft_split_whitespaces(str);
if (words == NULL)
{
perror("Split whitespace");
return EXIT_FAILURE;
}
ft_print_strlist(words);
ft_free_strlist(words);
return EXIT_SUCCESS;
}