/* * Illustrates some advanced array concepts */ #include using namespace std; void single_pointer(int *arg) { cout << "\t Inside function single_pointer:" << endl; cout << "\t\t int * = " << arg << endl; cout << "\t\t int = " << *arg << endl; int SIZE = 5; int *new_array = new int[SIZE]; for(int i = 0; i < SIZE; i++) { new_array[i] = 47; } arg = new_array; cout << "\t Inside function single_pointer:" << endl; cout << "\t\t int * = " << arg << endl; cout << "\t\t int = " << *arg << endl; } void double_pointer(int **arg) { cout << "\t Inside function double_pointer:" << endl; cout << "\t\t int ** = " << arg << endl; cout << "\t\t int * = " << *arg << endl; cout << "\t\t int = " << **arg << endl; int SIZE = 5; int * new_array = new int[SIZE]; for(int i = 0; i < SIZE; i++) { new_array[i] = 14; // Prof. Chambers' favorite number! } (*arg) = new_array; cout << "\t Inside function double_pointer:" << endl; cout << "\t\t int ** = " << arg << endl; cout << "\t\t int * = " << *arg << endl; cout << "\t\t int = " << **arg << endl; } int main() { int SIZE = 5; /****************************************************** * Lesson One: Constant pointers cannot be reassigned * ******************************************************/ int array1[SIZE]; int array2[SIZE]; // array1 = array2; /************************************************************************** * Lesson Two: Array names are converted to a pointer except in two cases * **************************************************************************/ // When an array is used in an expression, it is converted to the address of the first element *(array1+0) = 3; *(array1+1) = 3; *(array1+2) = 3; *(array1+3) = 3; *(array1+4) = 3; // The two exceptions are the sizeof operator and the addressof (&) operator // In these two cases, the array name refers to the entire array of N elements cout << "Number of bytes for *entire* array: " << sizeof(array1) << " bytes" << endl; cout << "Address of first element: " << array1 << endl; cout << "Address of entire array: " << &array1 << endl; cout << endl << endl; /******************************************************************* * Lesson Three: Dynamically allocated arrays are always pointers * *******************************************************************/ // array3 is a true pointer int *array3 = new int[SIZE]; cout << "Address in main: " << array3 << endl; single_pointer(array3); cout << "Address in main: " << array3 << endl; cout << endl << endl; cout << "Address in main: " << array3 << endl; double_pointer(&array3); cout << "Address in main: " << array3 << endl; cout << endl << endl; return 0; }