// ========================================================================== // $Id: element_access.cpp,v 1.5 2014/09/13 19:48:03 jlang Exp $ // CSI2372 example Code for lecture 3 // ========================================================================== // (C)opyright: // // Jochen Lang // SITE, University of Ottawa // 800 King Edward Ave. // Ottawa, On., K1N 6N5 // Canada. // http://www.site.uottawa.ca // // Creator: jlang (Jochen Lang) // Email: jlang@site.uottawa.ca // ========================================================================== // $Log: element_access.cpp,v $ // Revision 1.5 2014/09/13 19:48:03 jlang // Added C++11 features to lecture 3 // // Revision 1.4 2011/09/19 20:44:36 jlang // Added extra example for array name // // Revision 1.3 2008/09/13 01:36:53 jlang // Minor clarifications arrays and operators // // Revision 1.2 2007/09/18 00:24:50 jlang // Added comments // // Revision 1.1 2006/09/11 21:38:36 jlang // Check-in for lecture 3 // // // ========================================================================== #include #include using std::cout; using std::endl; using std::setw; int main() { // multi-dim. arrays are arrays of arrays // 3D int numbers3D[2][3][4] {{{0,1,2,3}, {4,5,6,7}, {8,9,10,11}}, {{12,13,14,15}, {16,17,18,19}, {20,21,22,23}}}; // 2D int numbers[3][4] {{0,1,2,3}, {4,5,6,7}, {8,9,10,11}}; // element access in 3D int element = numbers3D[1][2][0]; cout << element << endl; // array with 4 integers is a row // get a pointer to array of ints int (*row)[4] = &numbers[1]; // 3rd element in row 1 -- parantheses! // It is not the same as *(row[3])or *row[3] int elementA = (*row)[3]; cout << "elementA: " << elementA << endl; // Access via address of elements int* elementB = &numbers[0][2]; cout << "elementB: " << *elementB << endl; int* elementC = &numbers[0][1]; cout << "elementC: " << *elementC << endl; int* elementD = numbers[1]; cout << "elementD: " << *elementD << endl; // Array name is a const ptr int (*start)[4] = numbers; cout << "(*start)[1]: " << (*start)[1] << "\t *(*start+1): " << *(*start+1) << "\t or start[0][1]: " << start[0][1] << endl; return 0; }