How do I concatenate two arrays to get a single array containing the elements of both original arrays?
Generally speaking, in plain C, you can't merge two arrays.
The issue is that C does not really have arrays at all. The a[b]
notation is only syntactic sugar for point addition and dereference: *(a + b)
. The variable a
is only a pointer, so it does not record the array length, so concatenation is not possible.
So, how do we get the array length? Another question that needs answer is how should the new array be allocated?
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.