Fun with Pointers I
- Selvyn Wright
Owned by Selvyn Wright
Feb 27, 2019
1 min read
Loading data...
Basic Pointer Examples Expand source
// pointers.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> using std::cout; using std::endl; using std::end; struct time { int hour; int minute; int second; }; void handleTime(time tt) { tt.hour++; } void handleTime(time& tt, int amt) { tt.hour += amt; } void handleTime(time *tt) { tt->hour++; } void f2(int *pp) { cout << "f2::xp = " << *pp << endl; (*pp)++; } void f1(int *pp) { cout << "f1::xp = " << *pp << endl; f2(pp); (*pp)++; } int * f4() { int x = 45; return &x; } int * f3() { int *xp = f4(); return xp; } int gx = 99; int * f6() { ++gx; return &gx; } int * f5() { int *xp = f6(); ++(*xp); return xp; } void funWithLocalArray() { char msg[] = "Selvyn Wright"; char *cptr = msg; for (int idx = 0; msg[idx] != NULL; ++idx) cout << msg[idx]; cout << endl; while (*cptr) cout << *cptr++; cout << endl; cptr = msg; char c = *cptr; while (c) { cout << c; cptr++; c = *cptr; } cout << endl; } void pointerArithmetic() { char msg[] = "Selvyn Wright"; int intarray[] = { 11, 22, 33, 44, 55 }; double dblArray[] = { 11.11, 22.22, 33.33, 44.44, 55.55 }; char *cptr = msg; ++cptr; int *iptr = intarray; *(iptr + 2); iptr[2]; double *dptr = dblArray; ++dptr; } int main() { int x = 45; int *xp; xp = &x; cout << "Pre::xp = " << x << endl; f1(xp); cout << "Post::xp = " << x << endl; xp = f3(); int y = 33; f1(&y); cout << "Data from f4 = " << *xp << endl; xp = f5(); int z = 33; f1(&z); cout << "Data from f6 = " << *xp << endl; funWithLocalArray(); pointerArithmetic(); time myTime = { 12, 3, 1 }; time *tptr = &myTime; handleTime(myTime); handleTime(myTime, 1); handleTime(tptr); handleTime(*tptr, 1); return 0; }