Lecture 19

Reading

p.404-414

Pointer

What is pointers?

How to declare pointers?

Example 1: declare pointers
#include <iostream>
using namespace std;

int main() {
int *pointer, num = 5 ;
return 0;
}

Address-of operator

Example 2:Usage of &
#include <iostream>
using namespace std;

int main() {
int *pointer, num = 5;
pointer = &num; // assign the address of num to the pointer
cout << "The address of num is: "
<< pointer << endl;
return 0;
}

Output
The address of num is: 006AFDF0

Dereferencing operator

Example 3: Use dereferencing operator
#include <iostream>
using namespace std;

int main() {
int *pointer, num = 5;
pointer = &num;
cout << num << endl;
cout << *pointer << endl;
return 0;
}

Output
5
5

More examples

Example 4: What is the output of the following program?
#include <iostream>
using namespace std;

int main() {
double *pt, x = 3.15;
pt = &x;
cout << x << endl;
cout << *pt << endl;
x = 4.2; cout << x << endl; cout << *pt << endl; *pt = 12.59; cout << x << endl; cout << *pt << endl; return 0; }














Example 5: What is the output of the following program?
#include <iostream>
using namespace std;

int main() {
double *pt1, *pt2, x1 = 3.15, x2 = 2.44;
pt1 = &x1;
pt2 = &x2;
cout << x1 << " " << *pt1 << " "
<< x2 << " " << *pt2 << endl;
pt1 = pt2;
cout << x1 << " " << *pt1 << " "
<< x2 << " " << *pt2 << endl;
x2++;
cout << x1 << " " << *pt1 << " "
<< x2 << " " << *pt2 << endl;
pt2 = &x1;
x1 = 10.7;
x2 = 2.98;
cout << x1 << " " << *pt1 << " " << x2 << " " << *pt2 << endl; return 0; }














new operator

Refer to example 6, 7
Example 6: use of new operator
#include <iostream>
using namespace std;

int main() {
char *pt;
pt = new char; *pt = 'H'; cout << *pt << endl; return 0; }

Output
H








Example 7: What is the output of the following program
#include <iostream>
using namespace std;

int main() {
int *p1, *p2;

p1 = new int;
*p1 = 42;
p2 = p1;
cout << "*p1 == " << *p1 << endl; cout << "*p2 == " << *p2 << endl; *p2 = 53; cout << "*p1 == " << *p1 << endl; cout << "*p2 == " << *p2 << endl; p1 = new int;
*p1 = 88;
cout << "*p1 == " << *p1 << endl; cout << "*p2 == " << *p2 << endl; return 0; }