How do I concatenate two arrays to get a single array containing the elements of both original arrays?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Arrays in C simply are a contiguous area of memory, with a pointer to their start*. So merging them involves:
- Find the length of the arrays A and B, (you will probably need to know the number of elements and the
sizeof
each element) - Allocating (
malloc
) a new array C that is the size of A + B. - Copy (
memcpy
) the memory from A to C, - Copy the memory from B to C + the length of A (see 1).
- You might want also to de-allocate (
free
) the memory of A and B.
Note that this is an expensive operation, but this is the basic theory. If you are using a library that provides some abstraction, you might be better off. If A and B are more complicated then a simple array (e.g. sorted arrays), you will need to do smarter copying then steps 3 and 4 (see: how do i merge two arrays having different values into one array).
- Although for the purpose of this question, the pointer explanation will suffice, strictly speaking (and for pacifying the commenter below): C has the concept of an array, that can be used without the syntax of pointers. Implementation wise, however, a C array and a contiguous area of memory, with a pointer are close enough they can be, and often are, used interchangeably.