Arrays And Pointers
As indicated earlier, static arrays are referenced via a pointer variable. In C and C++, any pointer variable can be used as if it were an array because arrays and pointers are interchangeable. When the Pointer AssignmentSince the variable int *myPtr = gradeList; which results in the following It does not matter if the pointer assigned to
To direct a pointer to a specific element of an array use the address-of operator int *thirdElement = &gradeList[ 2 ]; Pointer SubscriptsWe can now use the new pointer int sum = 0; for( int i = 0; i < NUM_GRADES; i++ ) sum += myPtr[ i ]; When a subscript is applied to a pointer variable, C/C++ simply computes the actual address of the element based on the address in the pointer variable (
Since no range checking is performed, it is up to you to make sure your subscripts do not result in references that are out of bounds.
Arrays as ParametersAn alternate approach for specifying an array as an argument to function is to simply specify a pointer float avgGrade( int *theGrades, int num ) { int sum = 0; for( int i = 0; i < num; i++ ) sum += theGrades[ i ]; return sum / float( num ); } This works since an array is always referenced by a pointer and subscripts can be applied to any pointer variable. The C++ approach for specifying arrays as parameters is discussed in the [[Arrays] section. Pointer ArithmeticAnother special feature of pointers and arrays in C/C++ is the ability to perform pointer arithmetic. Consider the following example which is a modified version of an earlier code segment int *myPtr = gradeList; for( int i = 0; i < NUM_GRADES; i++ ) { printf( "%d\n", *myPtr ); myPtr += 1; } In this version, we no longer use a subscript to reference the array element. Instead, we
When a pointer is incremented, the address stored in that variable is incremented by the data type size to which the pointer references. In this case, the address is incremented by 4 since our pointer is a pointer to an Subtraction and multiplication can also be used with pointers to adjust the address stored in the variable. Dynamic ArraysArrays in C++ can also be created at runtime just as they are in Java. There are two approachs to creating dynamic arrays: C++ specific dynamic allocation or the original C allocation approach. To create a dynamic array using the C++ approach, the int *myGrades = new int[ NUM_GRADES ]; myGrades[ 0 ] = 85; myGrades[ 1 ] = 90; myGrades[ 2 ] = 87; myGrades[ 3 ] = 65; myGrades[ 4 ] = 91; we create a five element Note that the array itself is dynamic but it does not contain dynamic elements. You will also notice the use of the pointer notation to specify the array pointer variable. Deleteing Dynamic Arrays.
As with any dynamic variable, you are responsible for deallocation when the dynamic memory is no longer needed. The delete myGrades; You can only delete an array which was created using the
|