【发布时间】:2017-02-11 16:11:29
【问题描述】:
我有这个函数可以将一维数组转换为二维数组。当我转换它时,我需要在每个 4x4 方格之间保留一个 \n(换行符)。
int count_words(const char *str, char c)
{
int i;
int count;
i = 0;
count = 0;
while (str[i])
{
while (str[i] && str[i] == c)
i++;
if (str[i])
{
count++;
while (str[i] && str[i] != c)
i++;
}
}
return (count);
}
char *get_word(const char *str, char c)
{
char *word;
int i;
i = 0;
word = (char*)malloc(sizeof(char) * 500);
while (str[i] && str[i] != c)
{
word[i] = str[i];
i++;
}
word[i] = '\0';
return (word);
}
char **ft_strsplit(const char *s, char c)
{
char **split;
int words;
int i;
i = 0;
words = count_words(s, c);
split = (char**)malloc(sizeof(char*) * words + 1);
if (split == NULL)
return (NULL);
while (*s)
{
if (*s == c)
s++;
if (*s)
{
if (*s == c)
{
split[i] = ft_strdup("\0");
s++;
//printf("=========>%s\n", split[i]);
i++;
}
else{
split[i] = get_word(s, c);
s = s + ft_strlen(split[i]);
//printf("%s\n", split[i]);
i++;}
}
}
split[i] = NULL;
int k = 0;
while (split[k])
{
printf("%s\n", split[k]);
k++;
}
return (split);
}
这是输入文件:
这是转换成这个一维字符串(const char *s):
#...\n#...\n#...\n#...\n\n.#..\n.#..\n.#..\n.#..\n\n###.\n..#.\n....\n....\n\n....\n....\n....\n####\n
这就是输出,里面有随机的不可区分的字符。
#...
#...
#...
#...
.#..
.#..
.#..
.#..
�P@��
###.
..#.
....
....
....
....
....
####
为什么会出现随机字符?
【问题讨论】:
-
SO 不是调试服务。使用符号编译,在调试器中运行代码以逐行跟踪程序,检查相关变量的值以了解实际情况。如果出现具体问题,请随时返回此处。
-
我的话,这是一个调试服务。调试是发现一个逻辑错误。当 OP 提供可重复的示例和对程序的全面描述时,我们就是这样做的。
-
你怎么打电话给
ft_strsplit?中断字符应为\n。 -
count_words不计算分隔符。但是您使用分隔符为split[i] = ft_strdup("\0");。