// ------------------------------- // pointer.cpp // ------------------------------- #include "w.h" void main() { nl(0); banner("pointer.cpp"); int j = 3; int *pj; pj = &j; p("j = ",j); p(" pj = "); cout << pj; pl(" (HEX)"); double x = Pi; p("x = ",x); p(" &x = "); cout << &x << "\n"; int v[10]; for (j = 0; j < 5; j++) { v[j] = 20-j; cout << " v[" << j << "] = "; cout << v[j] << " "; cout << " &v[" << j << "] = "; cout << &v[j] << "\n"; } nl(); p("&v = "); cout << &v; nl(); p("&v[0] = "); cout << &v[0] << "\n"; nl(); int *pv = &v[0]; pv++; pv++; p("int *pv = &v[0], pv++, pv++, pv = "); cout << pv; p(" *pv = ", *pv); nl(); pv = &v[2]; pv = pv - 1; pl("pv = &v[2], pv = pv - 1, *pv = ", *pv); p("sizeof(int) = ", sizeof(int)); int vi[100]; vi[0] = 1; pl(" int vi[100]; sizeof(vi) = ", sizeof(vi)); p("sizeof(double) = ", sizeof(double)); double vx[100]; for (int i = 0; i < 100; i++) vx[i] = Pi; pl(" double vx[100]; sizeof(vx) = ", sizeof(vx)); nl(2); double *ux = NULL; p("*ux = NULL = "); cout << ux; nl(); ux = new double[1000]; // memory on the heap pl("ux = new double[1000]; sizeof(ux) = ", sizeof(ux)); p("sizeof(*ux) = ",sizeof(*ux)); pl(" sizeof(ux[0]) = ", sizeof(ux[0])); p("ux = "); cout << ux; delete [] ux; p(" delete [] ux; ux = "); cout << ux; nl(); ux = NULL; // safe p("ux = NULL; ux = "); cout << ux; pl(" safe now"); nl(2); cout.precision(25); x = 1.0; x = x/3; pl("1.0/3 = ",1.0/3); cout.precision(8); double *a[3]; // array of pointers to double x = 2.1; double y = 2.2,z = 2.3; p("x = ",x); p(" y = ",y); pl(" z = ",z); a[0] = &x; a[1] = &y; a[2] = &z; for (j = 0; j < 3; j++) { p("*a["); p(j); p("] = ", *a[j]); p(" "); } nl(); double t = *a[0]; *a[0] = *a[1]; *a[1] = t; p("x = ",x); p(" y = ",y); pl(" z = ",z); } /* ------------- pointer.cpp ------------- j = 3 pj = 0x243f290a (HEX) x = 3.14159 &x = 0x243f28fc v[0] = 20 &v[0] = 0x243f28a6 v[1] = 19 &v[1] = 0x243f28a8 v[2] = 18 &v[2] = 0x243f28aa v[3] = 17 &v[3] = 0x243f28ac v[4] = 16 &v[4] = 0x243f28ae &v = 0x243f28a6 &v[0] = 0x243f28a6 int *pv = &v[0], pv++, pv++, pv = 0x243f28aa *pv = 18 pv = &v[2], pv = pv - 1, *pv = 19 sizeof(int) = 2 int vi[100]; sizeof(vi) = 200 sizeof(double) = 8 double vx[100]; sizeof(vx) = 800 *ux = NULL = 0x00000000 ux = new double[1000]; sizeof(ux) = 4 sizeof(*ux) = 8 sizeof(ux[0]) = 8 ux = 0x2fb700be delete [] ux; ux = 0x2fb700be ux = NULL; ux = 0x00000000 safe now 1.0/3 = 0.333333333333333315 x = 2.1 y = 2.2 z = 2.3 *a[0] = 2.1 *a[1] = 2.2 *a[2] = 2.3 x = 2.2 y = 2.1 z = 2.3 */