Reputation: 51
How do I concatenate two arrays to get a single array containing the elements of both original arrays?
Upvotes: 9
Views: 46608
Reputation: 16338
Arrays in C simply are a contiguous area of memory, with a pointer to their start*. So merging them involves:
sizeof
each element)malloc
) a new array C that is the size of A + B.memcpy
) the memory from A to C,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).
Upvotes: 30