// Copyleft: Sathiamoorthy Manoharan. #include int main() { const int MYMAX = 16; int array[MYMAX]; for ( int i = 0; i < MYMAX; ++i ) { array[i] = i*i; } std::cout << "index\tvalue\taddress\n"; for ( int i = 0; i < MYMAX; ++i ) { std::cout << i << "\t" << array[i] << "\t" << (unsigned long) &array[i] << "\n"; } // Now we change the last element of the array // by picking the address of the last element of the array // and changing the content the address is pointing to. // This is equivalent to saying array[MYMAX-1] = 3737599 int* lastAddress = &array[MYMAX-1]; *lastAddress = 3737599; std::cout << "modified array:\n"; for ( int i = 0; i < MYMAX; ++i ) { std::cout << i << "\t" << array[i] << "\t" << (unsigned long) &array[i] << "\n"; } // Now we change the last element of the array again. // We compute the address of the last element of the array // from the address of the first element and the last element's // offset from the first element. // We then change the content the last address is pointing to. // This is equivalent to saying array[MYMAX-1] = 3737000 int* firstAddress = &array[0]; int* lastAddress2 = firstAddress + (MYMAX - 1); *lastAddress2 = 3737000; std::cout << "modified array:\n"; for ( int i = 0; i < MYMAX; ++i ) { std::cout << i << "\t" << array[i] << "\t" << (unsigned long) &array[i] << "\n"; } // In C/C++, the name of an array is in fact the address of the // first element of the array. Thus, '&array[0]' is equivalent // to 'array'. So we replace 'firstAddress' (i.e. &array[0]) by // simply 'array' here to compute the last address. int* lastAddress3 = array + (MYMAX - 1); *lastAddress3 = 2778000; std::cout << "modified array:\n"; for ( int i = 0; i < MYMAX; ++i ) { std::cout << i << "\t" << array[i] << "\t" << (unsigned long) &array[i] << "\n"; } return 0; }