TOPIC 10.1.1
Pointers
Intializing Pointers
int *countPtr; // Pointer declaration
// A pointer as a parameter
#includevoid f(int *); // This function has a pointer as a parameter main() { int y; f(&y); // Pass an address into the function return 0; } void f(int *xPtr)) // xPtr will hold the address of y { *xPtr = 100; }
Pointer Operators
// Attempting to modify data through a // non-constant pointer to constant data. #includevoid f(const int *); main() { int y; f(&y); // f attempts illegal modification return 0; } // In f, xPtr is a pointer to an integer constant void f(const int *xPtr) { *xPtr = 100; // cannot modify a const object }
Passing pointers to functions
4 Methods:
1. Non constant pointer to non constant data
// Non-constant pointer to non-constant data #includevoid f(int *); // This function has a pointer as a parameter main() { int y; f(&y); // Pass an address into the function return 0; } void f(int *xPtr)) // xPtr will hold the address of y { *xPtr = 100; }
2. Non constant pointer to constant data
// Attempting to modify data through a // non-constant pointer to constant data. #includevoid f(const int *); main() { int y; f(&y); // f attempts illegal modification return 0; } // In f, xPtr is a pointer to an integer constant void f(const int *xPtr) { *xPtr = 100; // cannot modify a const object }
3. Constant pointer to non constant data (the default for an array)
// Attempting to modify a constant pointer to // non-constant data #includemain() { int x, y; int * const ptr = &x; // ptr is a constant pointer to an // integer. An integer can be modified // through ptr, but ptr always points // to the same memory location. *ptr = 7; ptr = &y; // illegal modification of a constant pointer return 0; }
4. Constant pointer to constant data
// Attempting to modify a constant pointer to // constant data. #includemain() { int x = 5, y; const int *const ptr = &x; // ptr is a constant pointer to a // constant integer. ptr always // points to the same location and // the integer at that location // cannot be modified. cout << *ptr << endl; *ptr = 7; // illegal modification of a constant integer ptr = &y; // illegal modification of a constant pointer return 0; }
Relationship between Pointer and Arrays
int b[5] = {1,2,3}, *bPtr;
bPtr = b;
Arrays of Pointers
char *employee_lastname[100] = {"Webb", Smith", "Zhang", "Lo", "Pena"}
Function Pointers
// Function pointers #includemain () { void (*f[3])(int) = {f1, f2, f3}; *f[0]; //calls f1 *f[1]; //calls f2 *f[2]; //calls f3 return 0; } void f1() { return; } void f2() { return; } void f3() { return; }