Lecture 23

Reading

p500-506

Copy

#include<iostream>
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

Example
#include<iostream>
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