1.15.3. Exercises: Pointers and Memory Access

We need to add exercises here.

[ fromfile: pointers.xml id: None ]

  1. Predict the output of Example 1.32

    Example 1.32. src/pointers/newdelete1/newdelete1.cpp

    #include <QTextStream>
    
    int main() {
        QTextStream cout(stdout);
        const char tab = '\t';
        int n = 13;
        int* ip = new int(n + 3);
        double d = 3.14;
        double* dp = new double(d + 2.3);
        char c = 'K';
        char* cp = new char(c + 5);
        cout << *ip << tab << *dp << tab << *cp << endl;
        int* ip2 = ip;
        cout << ip << tab << ip2 << endl;
        *ip2 += 6;
        cout << *ip << endl;
        delete ip;
        cout << *ip2 << endl;
        cout << ip << tab << ip2 << endl;
        return 0;
    }
    
    

    <include src="src/pointers/newdelete1/newdelete1.cpp" href="src/pointers/newdelete1/newdelete1.cpp" id="newdelete1cpp" mode="cpp"/>


    Compile and run the code. Explain the output, especially the last two lines.

  2. Modify Example 1.30 to do some arithmetic with the value pointed to by jp. Assign the result to the location in memory pointed to by ip, and print the result. Print out the values from different places in the program. Investigate how your compiler and runtime system react to placement of the output statements.

  3. Read Chapter 21 and do experiments with the code examples.