How can I concatenate two arrays in C?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
In C programming, concatenating two arrays involves joining them end-to-end to form a new, single array. This process is vital when you need to combine data from two arrays into one, preserving the order of elements. Let's explore how we can achieve array concatenation in C, along with relevant technical explanations and examples.
Understanding Arrays in C
Arrays in C are collections of elements of the same data type, stored in contiguous memory locations. They are fixed in size, meaning you cannot alter their size once they have been created. To concatenate two arrays, you need to create a third array with adequate space to store the elements of both original arrays.
Steps for Concatenating Two Arrays
- Determine the sizes of both arrays.
- Create a new array with a size equal to the sum of the sizes of the two arrays you wish to concatenate.
- Copy elements from the first array into the new array.
- Copy elements from the second array into the new array immediately following the elements of the first array.
Implementation in C
Below is an example to demonstrate how to concatenate two arrays in C:
- In this example, two arrays
array1andarray2are concatenated. - A new integer array
resultis declared with a size equal to the sum of the sizes ofarray1andarray2. - The function
concatenateArraysutilizes twoforloops:- The first loop copies elements from
array1. - The second loop appends elements from
array2, starting from wherearray1ended.
- The concatenated result is then printed to the console.
- Memory Allocation: The new array must be large enough to hold all elements from the two input arrays. Memory allocation with
malloccan be used if you need the array to be dynamic. - Time Complexity: Concatenating arrays is an operation, where
nis the size of the first array andmis the size of the second array. This is due to the necessity of copying each element.

