C does not support direct assignment between arrays after declaration. To copy an array, each element can be copied individually using a loop.
#include <stdio.h>
int main(void)
{
int source[] = {10, 20, 30, 40, 50};
int destination[5];
for (int i = 0; i < 5; i++)
{
destination[i] = source[i];
}
printf("Source array: ");
for (int i = 0; i < 5; i++)
{
printf("%d ", source[i]);
}
printf("\nDestination array: ");
for (int i = 0; i < 5; i++)
{
printf("%d ", destination[i]);
}
printf("\n");
return 0;
}
Example Output #
Source array: 10 20 30 40 50
Destination array: 10 20 30 40 50
Explanation #
The source array contains five integer elements:
int source[] = {10, 20, 30, 40, 50};
The destination array reserves space for five integers:
int destination[5];
The loop copies each element at the corresponding index:
for (int i = 0; i < 5; i++)
{
destination[i] = source[i];
}
After the loop, both arrays contain the same values, but they remain separate array objects. Modifying an element in one array does not modify the corresponding element in the other.
Array Copying Methods #
| Method | Description |
|---|---|
| Element-by-element assignment | Copies individual elements using a loop |
memcpy() |
Copies a specified number of bytes between non-overlapping memory regions |
memmove() |
Copies a specified number of bytes and supports overlapping memory regions |
For arrays of ordinary numeric types, a loop is a straightforward way to copy elements. memcpy() and memmove() operate on bytes, so the byte count must be calculated correctly.
Direct array assignment is invalid in C:
destination = source; /* Invalid */
Array copying must use an appropriate element-wise or memory-copy operation.