首页 > 解决方案 > 复制以 NULL 结尾的字符串数组的子数组

问题描述

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

{"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().

标签: arrayscstringnull

解决方案


我有一个尝试:

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;
}

推荐阅读