C/C++ Copy Array

For Indonesian version visit  my blog at http://fsharing.blogspot.com/2011/01/cara-mengcopy-array-di-cc.html

When we create array in C/C++, we can copy one array to another by looping every element array with for or while command. Besides using this command, we can use memcpy command (we can must include string.h at header of my code). This is example how to copy array with looping and copy memory method.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
	int i;
	int n;
	int *A=NULL, *B=NULL, *C=NULL;

	n = 10;
	A = (int*) calloc(n, sizeof(int));
	B = (int*) calloc(n, sizeof(int));
	C = (int*) calloc(n, sizeof(int));

	for (i=0; i<n; i++)
		A[i] = i;

	for (i=0; i<n; i++)
		B[i] = A[i];

	memcpy(C, A, n*sizeof(int));
	printf("array A\n");
	for (i=0; i<n; i++)
		printf("%d  ",A[i]);
	printf("\n");	

	printf("array B\n");
	for (i=0; i<n; i++)
		printf("%d  ",B[i]);

	printf("\n");
	printf("array C\n");
	for (i=0; i<n; i++)
		printf("%d  ",C[i]);

	free(A);
	free(B);
	return (1);
}

To compile this program, I use this command :

gcc main.c -o tes

This is output from this code :

array A
0  1  2  3  4  5  6  7  8  9
array B
0  1  2  3  4  5  6  7  8  9
array C
0  1  2  3  4  5  6  7  8  9

Thank Gary for your info 🙂

Add a Comment

Your email address will not be published. Required fields are marked *