c - 将一个字符数组拆分为字符数组数组时,第一个数组始终显示为随机字符

标签 c arrays string

我正在做一个学校练习,它要求我们将一个字符串(字符数组)拆分为多个字符数组。像这样的字符串输入

"asdf qwerty zxcv"

应该产生像这样的字符数组数组

"asdf","qwerty","zxcv"

当我测试代码时,无论我输入什么字符串作为函数的参数,打印出来的第一个字符串始终是一些随机字符,而其余的则如预期。

"02�9�","qwerty","zxcv"

此外,我的代码在在线编译器中运行良好,我保存了 here 。我也在OnlineGDB中进行了测试,其中代码也运行得很好。

这是我的主要功能代码:

#include <stdio.h>
#include <stdlib.h>

int     is_separator(char c)
{
    if (c == '\n' || c == '\t' || c == ' ' || c == '\0')
    {
        return (1);
    }
    else
    {
        return (0);
    }
}

int     ct_len(int index, char *str)
{
    int     i;

    i = index;
    while (!(is_separator(str[index])))
    {
        index++;
    }
    return (index - i);
}

int     ct_wd(char *str)
{
    int     count;
    int     i;

    i = 0;
    count = 0;
    while (str[i])
    {
        if (is_separator(str[i]))
            count++;
        i++;
    }
    return (count + 1);
}

char    **ft_split_whitespaces(char *str)
{
    char    **tab;
    int     i;
    int     j;
    int     k;

    i = 0;
    j = 0;
    tab = malloc(ct_wd(str));
    while (str[j])
    {
        k = 1;
        while (is_separator(str[j]))
            j++;
        *(tab + i) = (char *)malloc(sizeof(char) * ((ct_len(j, str) + 1)));
        while (!(is_separator(str[j])))
        {
            tab[i][k - 1] = str[j++];
            k++;
        }
        tab[i++][k - 1] = '\0';
    }
    tab[i] = 0;
    return (&tab[0]);
}

int   main(void)
{
    char** res;

    for (res = ft_split_whitespaces("asdf qwerty zxcv"); *res != 0; res++)
    {
        printf("'%s',", *res);
    }
    return (0);
}

一个提示是第一个数组的输出正在改变,这表明我的内存分配可能存在一些问题。不过,我对此并不确定。如果您能帮我找出错误所在,我将非常感谢您的帮助。非常感谢您的阅读。

最佳答案

这个

tab = malloc(ct_wd(str));

到此

tab = malloc(ct_wd(str) * sizeof(char *));

您还可能会考虑使用 valgrind,它应该能够公平地指示损坏的位置。本质上,ct_wd(str) 函数以及之后的 malloc 语句是罪魁祸首。您可能想仔细看看您分配了多少内存以及实际使用了多少内存。如前所述,valgrind 应该可以更好地帮助您。

valgrind --tool=memcheck --leak-check=full --track-origins=yes <executalbe>

关于c - 将一个字符数组拆分为字符数组数组时,第一个数组始终显示为随机字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47118042/

相关文章:

c - C语言如何将文本读入数组

java - 将逗号分隔的 double 字符串拆分为 Java8 中的 double 组

c - ARM - 使用 16 位数据总线获取 32 位数据

c++ - 如何区分外接显示器和笔记本屏幕本身?

c - 如何检查以下数组是否包含这些字符?

arrays - 在接收函数返回数组时执行错误的过量操作?

c++ - 具有低冲突率的 32 位整数的快速字符串散列算法

c# - 全局设置 String.Compare/CompareInfo.Compare 为 Ordinal

c - 不确定在 char 中存储 BIGNUM 的参数 - BN_bn2bin()

不使用任何运算符检查数字是偶数还是奇数