关于如何在 C 中连接 char 数组的问题有很多,但我想知道的与此不同。我想知道如何在 C 中连接“双指针”字符数组。
例如,
const char *array1[] = {"aa", "bb"};
const char *array2[] = {"cc", "dd", "ee"};
我想像这样获取新的 char 双指针数组:
char **new_array = {"aa", "bb", "cc", "dd", "ee"};
// this code actually doesn't work, though
我想知道实现这一点的最简单和最快的方法。
编辑:事实上,我正计划在下面创建一个程序。
int main(int argc, char **argv) {
pid_t pid;
char **args = {"sh", "-c"} + argv; // this code doesn't work
posix_spawn(&pid, "/bin/sh", NULL, NULL, (char* const*)args, NULL);
}
这个程序只是在“sh -c”之后传递参数。
最佳答案
当然,只需为此分配一个缓冲区
#define _GNU_SOURCE 1
#include <stdio.h>
#include <strings.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
int main()
{
#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
const char * const array1[] = {"aa", "bb"};
const size_t array1_size = ARRAY_SIZE(array1);
const char * const array2[] = {"cc", "dd", "ee"};
const size_t array2_size = ARRAY_SIZE(array2);
const size_t concat_len = array1_size + array2_size;
const char ** const concat = malloc(concat_len * sizeof(*concat));
assert(concat != NULL);
for (size_t i = 0; i < concat_len; ++i) {
consr char *string_to_copy = i < array1_size ? array1[i] : array2[i - array1_size];
concat[i] = strdup(string_to_copy);
assert(concat[i] != NULL);
}
for (size_t i = 0; i < concat_len; ++i) {
printf("concat[%zu] = (%zu) '%s'\n", i, strlen(concat[i]), concat[i]);
}
for (size_t i = 0; i < concat_len; ++i) {
free(concat[i]);
}
free(concat);
return 0;
}
但我们应该能够做得更好。
关于在C中连接双指针char数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51785085/