// CS1621 Fall 2005 // Array access in C++ using indexing and pointers #include using namespace std; int main() { int A[100]; // With "normal" index access, we must evaluate the index expression // at each iteration through the loop. This can add some overhead to // access, especially if it is sequential through the array. for (int i = 0; i < 100; i++) { A[i] = i; cout << A[i] << " "; } cout << endl << endl; // With pointer access the pointer moves down the locations so that // at each iteration all we must do is derereference the pointer to // obtain the data for (int * p = A; p < A + 100; p++) { *p = 100 - (p - A + 1); cout << *p << " "; } cout << endl << endl; // Traditional 2-D array access using two index values int B[10][5]; for (int i = 0; i < 10; i++) { for (int j = 0; j < 5; j++) { B[i][j] = i+j; cout << B[i][j] << " "; } cout << endl; } cout << endl; // Single pointer 2-D array access. Note the deferencing of the // array when used with the pointer. This is because a 2-d array // in C++ is really a pointer to an array (as opposed to a pointer // to an int. Dereferencing the array gives us a pointer to an int // that is compatible with our normal pointer. // Note that if we are just iterating through the array, our pointer // access is again much more efficient than access by index. However, // if we need to calculate the i, j indexes anyway, we probably do not // save wih pointer access. for (int *p = *B; p < *(B + 10); p++) { int diff = p - *B; int i = (diff / 5); int j = (diff % 5); cout << "B[" << i << "][" << j << "] = " << *p << " "; if (j == 4) cout << endl; } }