#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
copy_n:
Copies exactly n elements from src[] to dst[].
This is the idiomatic C version of C++'s std::copy_n.
It uses memcpy because:
- memcpy is optimized in all standard C libraries
- It performs raw memory copying efficiently
- It avoids manual loops unless needed
Parameters:
src - pointer to the source array
dst - pointer to the destination array
n - number of elements to copy
Notes:
- Caller must ensure dst has enough space.
- Both arrays must contain the same type.
*/
void copy_n(const int *src, int *dst, size_t n) {
/* memcpy copies bytes, so we multiply by sizeof(int) */
memcpy(dst, src, n * sizeof(int));
}
int main(void) {
int src[] = {5, 10, 15, 20, 25, 30, 40, 60};
size_t total = sizeof(src) / sizeof(src[0]);
/* Number of elements we want to copy */
size_t n = 4;
/* Allocate destination array */
int *dst = malloc(n * sizeof(int));
if (!dst) {
fprintf(stderr, "Memory allocation failed\n");
return 1;
}
/* Perform the copy */
copy_n(src, dst, n);
/* Print results */
printf("Copying first %zu elements:\n", n);
for (size_t i = 0; i < n; i++) {
printf("%d ", dst[i]);
}
printf("\n");
free(dst);
return 0;
}
/*
run:
Copying first 4 elements:
5 10 15 20
*/