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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…