arrays - 复制以 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()
.
解决方案
我有一个尝试:
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;
}
推荐阅读
- android - 下面的代码在将密钥转换为字节数组后返回 null
- java - 我该如何做到这一点,以便将字符串变成只有单词之间有空格的单词?
- java - 如何在我的代码中实现 ASyncTask 以进行数据库操作
- c# - P/Invoke 未使用 StringBuilder 参数返回预期结果以调用 GetUserDefaultLocaleName()
- php - Laravel 7标签不显示
- python - 如何在字典列表中绘制值?
- python - 对python来说相对较新,我正在尝试编写一个测验,要求用户输入多个输入并用答案字典检查它们
- jquery - 刷新后如何使用jquery保存页面上的文本?
- sas - 在 sas 中使用 do 循环
- javascript - 如何在 vue-cli 中设置生产构建路径?