复制char指针数组

时间:2013-09-25 14:34:02

标签: c arrays string pointers

我想知道如何将以下容器复制到临时变量,以及如何定义该临时变量。

const char *containers_1[] = {"one","two","why do I stuck in this problem"};
const char *containers_2[] = {"Other","string","here"};

所以我正在寻找一个合适类型的临时变量,我可以将其中一个容器复制到。 "const char * container []"的声明来自一段我不想改变以保持格式的代码!

感谢您的时间。

1 个答案:

答案 0 :(得分:1)

代码应该改进,但我认为这就是你想要的。

const char *containers_1[] = {"one","two","why do I stuck in this problem"};
const char *containers_2[] = {"Other","string","here","whis","has","more"};

main(int argc, char **argv) {

char ** tmp1;
int i, size;

size = sizeof(containers_1);
printf ("%d\n", size);
tmp1 = malloc(size);
memcpy(tmp1, containers_1, sizeof(containers_1));

for (i=0; i< size/sizeof(char *); i++) {
    printf("%s\n", tmp1[i]);
    }

size = sizeof(containers_2);
printf ("%d\n", size);
tmp1 = malloc(size);
memcpy(tmp1, containers_2, sizeof(containers_2));

for (i=0; i< size/sizeof(char *); i++) {
    printf("%s\n", tmp1[i]);
   }
}