Pointers

Int A.cpp

#include <iostream>

using namespace std;

void main()

{ int i;

int *p,*q;

p = new int;

q = new int;

*p = 101;

*q = 102;

cout < "p = " < p < ' '

< *p < endl;

cout < "q = " < q < ' '

< *q < endl;

delete p;

delete q;

cout < endl;

p = new int;

q = new int;

*p = 103;

*q = 104;

cout < "p = " < p < ' '

< *p < endl;

cout < "q = " < q < ' '

< *q < endl;

delete p;

delete q;

}

Sample Run

p = 00480030 101

q = 00481FF0 102

p = 00481FF0 103

q = 00480030 104

Press any key to continue


Int B.cpp

#include <iostream>

using namespace std;

void main()

{ int i;

int *p,*q;

p = new int[5];

q = p+1;

cout < "p = " < p

< endl;

cout < "q = " < q

< endl;

cout < endl;

*p = 10;

*(p+1) = 20;

*(p+2) = 30;

*(p+3) = 40;

*(p+4) = 50;

for(i=0;i<5;i++)

cout < p+i < ' '

< *(p+i) < endl;

delete [] p;

}

Sample Run

p = 00481FE0

q = 00481FE4

00481FE0 10

00481FE4 20

00481FE8 30

00481FEC 40

00481FF0 50

Press any key to continue


Char.cpp

#include <iostream>

using namespace std;

void main()

{ int i;

char *p,*q;

p = new char;

*p = 'A';

cout < *p < endl;

delete p;

p = new char[5];

*p = 'A';

*(p+1) = 'B';

*(p+2) = 'C';

*(p+3) = 'D';

*(p+4) = 0;

q = p+1;

for(i=0;i<5;i++)

cout < *(p+i);

cout < endl;

cout < p < endl;

cout < q < endl;

}

Sample Run

A

ABCD

ABCD

BCD

Press any key to continue


Float.cpp

#include <iostream>

#include <iomanip>

#include <cmath>

using namespace std;

void main()

{ int i,n;

float *p;

cout < "Array size: ";

cin > n;

p = new float[n];

cout < "p = " < p

< endl;

cout < endl;

for(i=0;i<n;i++)

p[i] = sqrt(i);

cout < fixed;

cout < setprecision(4);

for(i=0;i<n;i++)

cout < i < ' '

< p[i] < endl;

delete [] p;

}

Sample Run

Array size: 10

p = 00491E10

0 0.0000

1 1.0000

2 1.4142

3 1.7321

4 2.0000

5 2.2361

6 2.4495

7 2.6458

8 2.8284

9 3.0000

Press any key to continue