## Lecture 23

p500-506

### Copy

 ```#include using namespace std; int main() { int a[] = {1,3,5,7,9}; int size = 5; int* b = a; // copy a to b int i; cout << "Array a: "; for(i = 0; i < size; i++) { cout << a[i] << " "; } cout << endl; cout << "Array b: "; for(i = 0; i < size; i++) { cout << b[i] << " "; } cout << endl; // change b b[2] = 10; cout << "Array a: "; for(i = 0; i < size; i++) { cout << a[i] << " "; } cout << endl; cout << "Array b: "; for(i = 0; i < size; i++) { cout << b[i] << " "; } cout << endl; return 0; } ```

Output
 ```Array a: 1 3 5 7 9 Array b: 1 3 5 7 9 Array a: 1 3 10 7 9 Array b: 1 3 10 7 9 ```
• copy `a` to `b`. `a` and `b` point to the same things.
• if you change `b`, `a` will be changed too.
• this is called shallow copy
• If you want to the original array `a` to remain unchanged, use deep copy
• copy the content of the array, instead of copying the pointer.

Example
 ```#include using namespace std; int main() { int a[] = {1,3,5,7,9}; int size = 5; int* b; int i; b = new int[size]; for(i = 0; i < size; i++) { b[i] = a[i]; // copy a[i] to b[i] } cout << "Array a: "; for(i = 0; i < size; i++) { cout << a[i] << " "; } cout << endl; cout << "Array b: "; for(i = 0; i < size; i++) { cout << b[i] << " "; } cout << endl; // change b b[2] = 10; cout << "Array a: "; for(i = 0; i < size; i++) { cout << a[i] << " "; } cout << endl; cout << "Array b: "; for(i = 0; i < size; i++) { cout << b[i] << " "; } cout << endl; return 0; } ```

Output
 ```Array a: 1 3 5 7 9 Array b: 1 3 5 7 9 Array a: 1 3 5 7 9 Array b: 1 3 10 7 9 ```