连接两个字符串数组? [英] Concatenating two arrays of strings?
问题描述
我是C语言世界的新手,我想将两个数组合并为一个数组,我对如何做到这一点有一个想法,但它不起作用:P
I am new to the c world and I want to merge two arrays into one array, i have one idea how to do this, but it doesnt work :P
char *s_one[] = { "Zorro", "Alex", "Celine" };
char *s_two[] = { "Zorro1", "Alex1"};
char *p = (char*)malloc((sizeof(s_one)+sizeof(s_two))*sizeof(char));
memcpy(p, s_one, sizeof(s_one));
memcpy(p + sizeof(s_one), s_two, sizeof(s_two));
//print out
for (count = 0; count < sizeof(p); count++)
printf("\narr[%d] = %c.", count, p[count]);
输出只是一些随机字符... 我做错了,在此先感谢您的小费
the output is just some random characters... what i am doing wrong, thanks in advance for every tipp
输出应为: 佐罗 亚历克斯 席琳 佐罗1号 亚历克斯1
the output should be: Zorro Alex Celine Zorro1 Alex1
推荐答案
我建议不要迭代使用memcpy,而要遍历两个数组中的每个数组,并使用strcpy将一个字符串从源数组复制到p中. memcpy的问题在于,它应该省略复制\ 0字符,因此是您的随机字符.
Instead of using memcpy I would recommend to iterate over each of the two arrays and copy one string from the source array into p using strcpy. The problem of memcpy is that it should omit to copy the \0 character, hence your random characters.
您的malloc指令很好.
You malloc instruction is fine.
这篇关于连接两个字符串数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!