【问题标题】:Copy sub-arrays of NULL-terminated array of strings复制以 NULL 结尾的字符串数组的子数组
【发布时间】:2021-01-22 13:13:21
【问题描述】:

假设我有一个“字符串数组”数组:

{"hello", "I", "am", "C", NULL, "And", "I", "am", "C++", NULL, "Now", "this", "is", "Java", NULL, NULL}

我怎样才能从这个数组中提取出NULL-终止的子数组,以便我可以拥有以下内容:

char* arr1[] = {"hello", "I", "am", "C", NULL}
char* arr2[] = {"And", "I", "am", "C++", NULL}
char* arr3[] = {"Now", "this", "is", "Java", NULL}

这个数组本身作为参数传递给函数,如下所示:

void function(char* strings[])
{
    int index = 0; 
    loop: 
    while(strings[index])
    {
        if(!strings[index + 1]) break;
        // how can I add stuff to an array? 
        ++index;
    }
    if (strings[index] || strings[index + 1]) goto loop;
    // Now what? 
}

编辑:我想要字符串的实际副本,可能是strdup()

编辑 2:我的尝试添加了,因为这是被要求的(我应该在一开始就提供它)。此外,该函数不需要返回任何内容:所有处理都在内部完成,然后字符串被丢弃(或存储在其他地方),因此strdup()

【问题讨论】:

  • 你应该只循环输入数组,当你找到一个 NULL 时结束一个子数组。
  • 应该只复制指针还是需要复制实际的字符串?
  • 不可能知道结果中有多少以 null 结尾的字符串数组。 function 的返回类型应该是 char*** 而不是 void
  • OT:将子字符串存储在 3 个不同的数组中似乎是一个相当糟糕的主意。这样做意味着该函数将无法处理具有 4 或 5 或 ... 或 100 个子字符串的输入。使用指向 char 指针数组的指针数组。
  • 无论如何 - 对于这个任务realloc是你的朋友

标签: arrays c string null


【解决方案1】:

我有一个尝试:

char*** group_strings(const char *strings[])
{
    uint index = 0;
    uint start_index = 0;
    uint num_groups = 0;
    uint *group_sizes = NULL;
    char ***grouped_strings = NULL;

    do
    {
        while (strings[index])
        {
            if (!index || !strings[index - 1]) start_index = index;
            if (!strings[index + 1]) break;
            ++index;
        }

        group_sizes = !group_sizes ? (uint *) calloc(++num_groups, sizeof(int))
                                   : (uint *) realloc(group_sizes, ++num_groups * sizeof(int));
        uint current_grp_size = index + 1 - start_index;
        group_sizes[num_groups - 1] = current_grp_size;

        char **current_argument = (char **) calloc(current_grp_size, sizeof(char *));
        for (int i = 0; i < index + 1 - start_index; ++i)
        {
            current_argument[i] = strdup(strings[start_index + i]);
        }

        grouped_strings = !grouped_strings ? (char ***) calloc(1, sizeof(char **))
                                           : (char ***) realloc(grouped_strings, (num_groups - 1) * sizeof(char **));
        grouped_strings[num_groups - 1] = current_argument;

        index += 2;
        if (!strings[index - 1] && !strings[index]) break;
    } while (strings[index] || strings[index + 1]);
    return grouped_strings;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-01
    • 2019-10-28
    • 2017-12-12
    • 1970-01-01
    • 2021-02-08
    • 2011-02-14
    • 1970-01-01
    • 2015-05-16
    相关资源
    最近更新 更多