#include <iostream>
using namespace std;
void main() {
int *pointer, num = 5 ;
char line[100];
cin.getline(line,100);
}
|
type *variableNameint *pt declares a integer pointer. An
integer pointer is a address on an integer variable.
#include <iostream>
using namespace std;
void main() {
int *pointer, num = 5;
pointer = # // assign the address of num to the pointer
cout << "The address of num is: "
<< pointer << endl;
char line[100];
cin.getline(line,100);
}
|
The address of num is: 006AFDF0 |
&variable gives the address of the
variable.
#include <iostream>
using namespace std;
void main() {
int *pointer, num = 5;
pointer = # // address of num
cout << num << endl;
cout << *pointer << endl; // the value the pointer points to.
char line[100];
cin.getline(line,100);
}
|
5 5 |
#include <iostream>
using namespace std;
void 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;
char line[100];
cin.getline(line,100);
}
|
3.15 3.15 4.2 4.2 12.59 12.59 |
#include <iostream>
using namespace std;
void main() {
double *pt1, *pt2, x1 = 3.15, x2 = 2.44;
pt1 = &x1; // pt1 points to x1
pt2 = &x2; // pt2 points to x2
cout << x1 << " " << *pt1 << " "
<< x2 << " " << *pt2 << endl;
pt1 = pt2; // pt1 points to what pt2 points to, i.e, x2
cout << x1 << " " << *pt1 << " "
<< x2 << " " << *pt2 << endl;
x2++; // both pt1 and pt2 point to x2, the value of x2 has been changed.
cout << x1 << " " << *pt1 << " "
<< x2 << " " << *pt2 << endl;
pt2 = &x1; // pt2 points to x1, pt1 still points to x2
x1 = 10.7;
x2 = 2.98;
cout << x1 << " " << *pt1 << " "
<< x2 << " " << *pt2 << endl;
char line[100];
cin.getline(line,100);
}
|
3.15 3.15 2.44 2.44 3.15 2.44 2.44 2.44 3.15 3.44 3.44 3.44 10.7 2.98 2.98 10.7 |
new operator
#include <iostream>
using namespace std;
void main() {
char *pt;
pt = new char; //pt is an address of a character. It points to a char
*pt = 'H';
cout << *pt << endl;
char line[100];
cin.getline(line,100);
}
|
H |
#include <iostream>
using namespace std;
void main() {
int *p1, *p2;
p1 = new int; // p1 points to an integer
*p1 = 42; // set the value of p1 points to to 42
p2 = p1; // p2 and p1 points to the same integer
cout << "*p1 == " << *p1 << endl;
cout << "*p2 == " << *p2 << endl;
*p2 = 53; // set the value of p2 points to to 53
cout << "*p1 == " << *p1 << endl;
cout << "*p2 == " << *p2 << endl;
p1 = new int; // p1 points to a new integer integer
*p1 = 88; // set the value of p1 points to to 88
cout << "*p1 == " << *p1 << endl;
cout << "*p2 == " << *p2 << endl;
char line[100];
cin.getline(line,100);
}
|
*p1 == 42 *p2 == 42 *p1 == 53 *p2 == 53 *p1 == 88 *p2 == 53 |