C programming
arrays
concatenation
coding tutorial
programming basics

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

  1. Determine the sizes of both arrays.
  2. Create a new array with a size equal to the sum of the sizes of the two arrays you wish to concatenate.
  3. Copy elements from the first array into the new array.
  4. 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 array1 and array2 are concatenated.
  • A new integer array result is declared with a size equal to the sum of the sizes of array1 and array2.
  • The function concatenateArrays utilizes two for loops:
    • The first loop copies elements from array1.
    • The second loop appends elements from array2, starting from where array1 ended.
  • 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 malloc can be used if you need the array to be dynamic.
  • Time Complexity: Concatenating arrays is an O(n+m)O(n + m) operation, where n is the size of the first array and m is the size of the second array. This is due to the necessity of copying each element.

Course illustration
Course illustration

All Rights Reserved.