Hi,
An exercise in my book asks me to define a second array initialised as a copy from the first array. I thought that you couldn't copy arrays?
Would it simply be a case of looping through and initialising each element?
Thanks.
Hi,
An exercise in my book asks me to define a second array initialised as a copy from the first array. I thought that you couldn't copy arrays?
Would it simply be a case of looping through and initialising each element?
Thanks.
Depends on the definition of "copy". You can copy each element and make a second array with separate memory, or you can copy the pointer and have two arrays that point to the same spaces in memory.
If the first, then you stated one way of copying an array. If the second...
int* array2 = array1; // copied array1
This isn't really much of an exercise as it is a lesson in memory/array management.
Thanks. So if I wanted 2 copies of the array I would use my first example, however if I wanted the same array to be copied, I would simply use a pointer?
Thanks for the help.
The difference lies in how you are managing the memory. The way I showed copies a pointer, which means you are accessing the exact same elements as the other array. Edit something in one array, and it will also change in the other.
The way you described makes a second copy of the memory, so each array has its own. If I edit something in one array, it will not be seen in the other.
Look at these examples.
Code:#include <stdio.h> #include <iostream> using namespace std; int main() { int* a1 = new int[100]; // 100 integers int* a2 = a1; a1[0] = 5; cout<< a1[0] << " " << a2[0] << endl; a2[0] = 10; cout<< a1[0] << " " << a2[0] << endl; int a3[100] = {1}; // 100 integers, all set to 1 int a4[100]; // 100 integers, different memory for(int i = 0; i < 100; i++) { a4[i] = a3[i]; // copy } cout<< a3[0] << " " << a4[0] << endl; a4[0] = 10; cout<< a3[0] << " " << a4[0] << endl; return 0; }