300 likes | 415 Views
Chapter 9 – Pointers Getting the address of a Variable. Why do we have pointers? Indirection – difference between Will you go out with me? Will you go out with person whose name is on cafeteria door? The address operator (&) returns the memory address of a variable.
E N D
Chapter 9 – PointersGetting the address of a Variable • Why do we have pointers? • Indirection – difference between • Will you go out with me? • Will you go out with person whose name is on cafeteria door? • The address operator (&) returns the memory address of a variable. Starting out with C++
Addresses: for our machines:char 1int 4, short int 2float 4 Starting out with C++
Use of & Operator – Program // This program uses the & operator to determine a variable’s // address and the sizeof operator to determine its size. sizeof(type) is also okay sizeof(array) gives length of types * number in array sizeof(pointer) gives length of pointer itself (4 for us) #include <iostream.h> void main(void) { int arr[10]; int X = 25; int * a = new int[10]; cout << "The address of X is " << &X << endl; cout << "The size of X is " << sizeof(X) << " bytes\n"; cout << "The value in X is " << X << endl; } // main Starting out with C++
Pointer Variables • Pointer variables, which are often just called pointers, are designed to hold memory addresses. • With pointer variables you can indirectly manipulate data stored in other variables. Starting out with C++
Pointer Variables – Program // This program stores the address of a variable in a pointer. #include <iostream.h> void main(void) { int X = 25; int *Ptr; //I like to read this backwards Ptr = &X; // Store the address of X in Ptr cout << "The value in X is " << X << endl; cout << "The address of X is " << Ptr << endl; }// main Note * and & are overloaded operators – you have seen them for other uses. Starting out with C++
Draw pictures to help you understand:int num1, num2=10; float f1=2.5; float * fptr; int * iptr; iptr = &num2; *iptr = 50; fptr = & f1; num1 = num2 + *iptr * *fptr; What is the value of num1? Starting out with C++
Pointer Variables What about taking the address of an address? int ** addP; addP = &Ptr Only works if address is actually stored somewhere Starting out with C++
Indirection Operator – Program // This program demonstrates the use of the indirection // operator. #include <iostream.h> void main(void) { int X = 25; int *Ptr; Ptr = &X; // Store the address of X in Ptr cout << "Here is the value in X, printed twice:\n"; cout << X << " " << *Ptr << endl; *Ptr = 100; // Note indirection is a unary operator cout << "Once again, here is the value in X:\n"; cout << X << " " << *Ptr << endl; } // main Starting out with C++
Note int * x,y is the same as int *x; int y; Starting out with C++
At Seats • Write the code to read in an integer, access it via a pointer, add five to it, and then print it out. • Why are we using pointers? No real purpose here – just to show we can and to gain experience. Starting out with C++
Relationship Between Arrays and Pointers • Array names can be used as pointers, and vice-versa. • This is important in understanding how arrays are passed. • This is also important in allocating dynamic arrays. Starting out with C++
Write a function void clear_array(int array[], int size) which sets each element of the array to zero. Try it three different ways (two with pointers) Starting out with C++
Here is the simplest way void clear(int a[], int size){ for (int i =0;i < size; i++) a[i] = 0; } Starting out with C++
void clear(int a[], int size){ int * p; for (int* p=a;p < a+size; p++) *p = 0; } Starting out with C++
void clear(int a[], int size){ for (int i =0;i < size; i++) *(a+i) = 0; } Starting out with C++
At seats • Write a function int replace_char(char *str, char old_char, char new_char) which replaces each occurrence of the character old_char with the character new_char in the string str. The function should return the number of characters actually replaced. Starting out with C++
Repeat the previous exercise accessing the array via pointers Starting out with C++
Arrays and Pointers – Program #include <iostream.h> void main(void) { short Numbers[] = {10, 20, 30, 40, 50}; // short *Numbers; would be similar, but no space allocated // an array of short and a pointer to short are the // SAME type to the compiler cout << "The first Oth element of the array is "; cout << *Numbers << endl; cout << "The third element of the array is "; cout << *(Numbers + 2) << endl; // Note, smart enough to add not just 2 but 2 times // the length of the type pointed to! } // main Starting out with C++
Using Pointer Arithmetic Starting out with C++
Pointers and Arrays – Program #include <iostream.h> void main(void) { int Numbers[5]; cout << "Enter five numbers: "; for (int Count = 0; Count < 5; Count++) cin >> *(Numbers + Count); cout << "Here are the numbers you entered:\n"; for (int Count = 0; Count < 5; Count++) cout << *(Numbers + Count)<< " "; cout << endl; } // main Starting out with C++
Consider these two swaps.What happens when you pass two pointers to each? • void swap(int *p, int*q){ • int * t = p; • p = q; • q = t; • } • void swap2( int *p, int *q){ • int *t = new int(); • *t = *p; • *p = *q; • *q = *t; • } Starting out with C++
Dynamic Arrays – Program float *Sales; int NumDays; Sales = new float[NumDays]; … delete [] Sales; float Sales2[10]; // Sales2 is a constant pointer Starting out with C++
At seats Define an int* pointer variable a. Then: (1) Use new to make a point to a dynamic array of 5 cells of type int. (2) Write a loop to fill a with values 3, 7, 11, 15, 19. Starting out with C++
At seats • Write code to read in the size of an array from input. • Allocate an array of strings of that size • Print them out backwards (last string first) using pointer variables (rather than subscripts) Starting out with C++
Try this: Assume int x[5] = {0, 1, 2, 3, 4}. What does print3(&x[0]) print? print3(&x[2])? print3(&x[4])? void print3(int x[]) { int i; for (i = 0; i < 3; i++) cout << x[i] << " "; cout << endl; } Starting out with C++
Pointer Arithmetic • Some mathematical operations may be performed on pointers. • The ++ and -- operators may be used to increment or decrement a pointer variable. • An integer may be added to or subtracted from a pointer variable. This may be performed with the +, -, +=, or -= operators. • A pointer may be subtracted from another pointer. (gives number of items between them not physical length) Starting out with C++
Pointer Arithmetic – Program #include <iostream.h> void main(void) { int Set[8] = {5, 10, 15, 20, 25, 30, 35, 40}; int *Nums, Index; Nums = Set; cout << "The numbers in Set are:\n"; for (Index = 0; Index < 8; Index++) {cout << *Nums << " "; Nums++; } // for cout << "\nThe numbers in Set backwards are:\n"; for (Index = 0; Index < 8; Index++) {Nums--; cout << *Nums << " "; } // for } // main Starting out with C++
Comparing Pointers • If one address comes before another address in memory, the first address is considered “less than” the second. • C++’s relational operators maybe used to compare pointer values. Starting out with C++
Pointers as Function Parameters • A pointer can be used as a function parameter. • It gives the function access to the original argument, much like a reference parameter does. Starting out with C++
Dynamic Memory Allocation • Variables may be created and destroyed while a program is running. This is help for linked lists. • A pointer than contains the address 0 is called a null pointer. • Use the new operator to dynamically allocate memory. • Use delete to dynamically deallocate memory. Starting out with C++