Monday 20 February 2012

Copy One Dimensional Arrays in C++

If you have two integer variables, you can easily copy the value of one to the other with this code:

int1 = int2;

If you try the same thing with arrays,

mArray1 = mArray2;

the code will not compile. You will get a compile error message.

Each element of the array has to be assigned from one variable to the other.

Sample Code:

The sample code will create array variables, A and B, of integer type. Values are assigned to each element of A then copied to B.

The sample code was created in MS Visual C++ as a Windows Form Application. It contains a form (Form1) that displays when the program runs. The sample code, contained in the Form Load Event, executes and adds text to a RichTextBox named rtOut.

// Declare one-dimension arrays.
int A[10], B[10];
rtOut->Text = "Declare two one-dimension arrays: ";
rtOut->Text += "int A[10], B[10]; \n\n";

// Declare counter.
int i = 0;

// Load array with multiples of 10s.
rtOut->Text += "Load array A with multiples of 10s. \n\n";
for (i; i < 10; i++) A[i] = i * 10;

// Copy value of A to B.
// Can't use: A = B;
rtOut->Text += "Copy value of A to B, element by element with B[i] = A[i]. \n\n";
// Counter i reset to 0.
for (i = 0; i < 10; i++) B[i] = A[i];

// Show content.
// Counter i reset to 0.
for (i = 0; i < 10; i++)
{
rtOut->Text += "The A[" + i + "] value is " + A[i] + ". The B value is " + B[i] + "\n";
}

Output:

Declare two one-dimension arrays: int A[10], B[10];

Load array A with multiples of 10s.

Copy value of A to B, element by element with B[i] = A[i].

The A[0] value is 0. The value of B at index 0 is 0
The A[1] value is 10. The value of B at index 1 is 10
The A[2] value is 20. The value of B at index 2 is 20
The A[3] value is 30. The value of B at index 3 is 30
The A[4] value is 40. The value of B at index 4 is 40
The A[5] value is 50. The value of B at index 5 is 50
The A[6] value is 60. The value of B at index 6 is 60
The A[7] value is 70. The value of B at index 7 is 70
The A[8] value is 80. The value of B at index 8 is 80
The A[9] value is 90. The value of B at index 9 is 90



1 comment:

  1. Can you do memcpy with 1-dimensional array? Is it faster than for loop?

    ReplyDelete