Debugging Pointers Introduction What are pointers for? Here are some common uses:
Accessing array elements
Passing arguments to a function when the function
needs to modify the original argument
Passing arrays and strings to functions
Obtaining memory from the system
Creating data structures such as linked lists
Addresses and Pointers Every byte in the computer’s memory has an address.
Addresses are numbers, just as they are for houses on a
street.
The numbers start at 0 and go up from there—1, 2, 3,
and so on.
If you have 1MB of memory, the highest address is
1,048,575. Addresses and Pointers The Address-of Operator & Out Put Pointer Variables Working Types of Pointers Accessing the Variable Pointed To Manipulating Values Summary so far Void Pointer Converting pointers Pointers and Arrays Pointers and Arrays Explanation Pointer Constants & Pointer Variables Passing Simple Variables Working Passing Arrays Sorting Array Elements OutPut Sorting The Bubble Sort Bubble Sort Pointers to String Constants Strings as Function Arguments Copying String Using Pointe The const Modifier and Pointers const int* cptrInt; //cptrInt is a pointer to constant int you cannot change the value of whatever cptrInt points to, although you can change cptrInt itself.
int* const ptrcInt;
//ptrcInt is a constant pointer to int you can change what ptrcInt points to, but you cannot change the value of ptrcInt itself.
char* strcpy(char* dest, const char* src);
Arrays of Pointers to Strings // ptrtostr.cpp // an array of pointers to strings #include <iostream>
using namespace std;
const int DAYS = 7; //number of pointers in array int main() { //array of pointers to char char* arrptrs[DAYS] = { “Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday” };
for(int j=0; j<DAYS; j++) //display every string
cout << arrptrs[j] << endl;
return 0;
} Memory Management: new and delete
cin >> size; // get size from user
int arr[size]; // error; array size must be a constant
int main() { char* str = “Idle hands are the devil’s workshop.”; int len = strlen(str); //get length of str char* ptr; //make a pointer to char ptr = new char[len+1]; //set aside memory: string + ‘\0’ strcpy(ptr, str); //copy str to new memory area ptr cout << “ptr=” << ptr << endl; //show that ptr is now in str delete[] ptr; //release ptr’s memory return 0; }