User Tools


using namespace std;

main() {
        //First we create an array of 10 ints
        int array[10] = {9,8,7,6,5,4,3,2,1,0};
        //array with no index refers to the address where 
        //the first element of the array is stored.
        //So array is a pointer
        cout << "array is at " << array << endl;

        //We can explicitly declare our own pointer and direct it to the 
        //same place that array points.
        int *pointer = array;
        cout << "pointer points at " << pointer << endl;

        //Now pointer and array act identically as far as indexing 
        //specific integer elements...
        cout << "i\tarray[i]\tpointer[i]" << endl;
        for (int i = 0; i < 10; ++i) {
                cout << i << "\t" << array[i] << "\t\t" << pointer[i] << endl;
        }

        //If we dereference with "*", we get the value of the integer at the 
        //address.  Since both array and pointer point at the first element
        //of the array, we get the value of that element (in this case 9)
        cout << "array deferenced is   " << (*array) << endl;
        cout << "pointer deferenced is " << (*pointer) << endl;

        //We make a new integer variable
        int value = 8;
        //We can get its address in memory with the address-of operator, "&"
        //Then we change pointer to point at that address
        pointer = (&value);

        //Verify what we've done with the address-of operator and 
        //dereferencing operator
        cout << "Value is equal to     " << value << endl;
        cout << "Address of value is   " << &value << endl;
        cout << "Pointer now points to " << pointer << endl;
        cout << "Value at pointer is   " << (*pointer) << endl;

        //We can use the dereferencing operator to change the value that 
        //is pointed at by pointer.
        //Note that since this actually changes the value at that address
        //in memory, the value of the variable "value" is changed as well.
        cout << "Changing value at pointer..." << endl;
        (*pointer) = 10;
        cout << "Pointer still points to " << pointer << endl;
        cout << "Value at pointer is     " << (*pointer) << endl;
        cout << "Address of value is     " << &value << endl;
        cout << "Value is now equal to   " << value << endl;

}

Top