我的程序有问题。 我的程序使用\t\n 或空格分割单词,并将单词放入字符串数组中。 当我像这样调用我的函数时,它工作得很好:
ft_print_words_tables(ft_split_whitespaces("Hello Everyone this is a test"));
但是当我尝试发送第一个命令行参数时,如下所示:
ft_print_words_tables(ft_split_whitespaces(argv[1]));
我收到以下错误:
./a.out“测试测试味道”
a.out(97132,0x7fff706ff000) malloc: * 对象 0x7f9e09403228 错误: 已释放对象的校验和不正确 - 对象可能在释放后被修改。
*在malloc_error_break中设置断点进行调试
[1] 97132 abort ./a.out“测试测试味道”
这是代码:
#include <stdlib.h>
// This func return the word nbr
int ft_compte_mot(char *str) {
int i = 0;
int j = 0;
while(str[i] == ' ' || str[i] == '\t' || str[i] == '\n') {
i++;
while (str[i] != '\0') {
if ((str[i] == ' ' || str[i] == '\n' || str[i] == '\t') &&
(str[i + 1] >= '!' && str[i + 1] <= 'z')) {
j++;
}
i++;
}
return (j + 1);
}
// this func count the word lenght and put them in an int array
int *ft_compte_taille_mot(int *taillemot, char *str) {
int i = 0;
int j = 0;
int k = 0;
while (str[i] != '\0') {
j = 0;
while ((str[i] == ' ' || str[i] == '\n' || str[i] == '\t')
&& str[i] != '\0')
i++;
while (str[i] != ' ' && str[i] != '\n' && str[i] != '\t'
&& str[i] != '\0') {
j++;
i++;
}
taillemot[k] = j;
i++;
k++;
}
return (taillemot);
}
void ft_copy_word(int *taillemot, int nbmot, char **tab, char *str) {
int i = 0;
int j = 0;
int k = 0;
while (str[i] != '\0' && k < nbmot) {
j = 0;
while ((str[i] == ' ' || str[i] == '\n' || str[i] == '\t')
&& str[i] != '\0')
i++;
while (j < taillemot[k]) {
tab[k][j] = str[i];
j++;
i++;
}
//tab[k][j] = '\0';
i++;
k++;
}
tab[nbmot] = 0;
}
char **ft_split_whitespaces(char *str) {
int nbmot = ft_compte_mot(str);
int *taillemot;
int i = 0;
char **string;
if ((taillemot = (int*)malloc(sizeof(int) * nbmot)) == NULL)
return (NULL);
ft_compte_taille_mot(taillemot, str);
if ((string = (char **)malloc(sizeof(char *) * (nbmot + 1))) == NULL)
return (NULL);
while (i < nbmot) {
if ((string[i] = (char *)malloc(sizeof(char) * taillemot[i] + 1))
== NULL)
return (NULL);
i++;
}
ft_copy_word(taillemot, nbmot, string, str);
return (string);
}
void ft_putchar(char c) {
write(1, &c, 1);
}
void ft_putstr(char *str) {
int i = 0;
while (str[i] != '\0') {
ft_putchar(str[i]);
i++;
}
}
void ft_print_words_tables(char **tab) {
int i;
i = 0;
while (tab[i] != 0) {
ft_putstr(tab[i]);
ft_putchar('\n');
i++;
}
ft_putchar('\n');
}
编辑:这是主要的编辑 2:我还使用 argv[1] 进行了测试
char **ft_split_whitespaces(char *str);
void ft_print_words_tables(char **tab);
void ft_putchar(char c)
{
write(1, &c, 1);
}
int main(int argc, char **argv)
{
ft_print_words_tables(ft_split_whitespaces(argv[1]));
return (0);
}
仅供引用,我在学校,我们有一个特定的规范,我们不能使用 for 循环或一堆 libc 函数。 我真的被困在这里,我真的不明白为什么它可以与“”一起使用,但不能与 **argv 一起使用
提前感谢您的帮助
最佳答案
我找到了解决方案:
char *str;
str = argv[1];
str[strlen(str) + 1] = '\0';
ft_print_words_tables(ft_split_whitespaces(str));
return (0);
感谢您的帮助
关于c - 按特定字符拆分单词适用于字符串,但不适用于 argv[1],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45252458/