Programming and Graphics

(Kiana) #1

5.1 Pointers to scalars and characters 129


or


double *pname

Similar declarations are made for other types.


Once declared, a pointer can be evaluated using thereference operator,
(&). For example, ifpnameis a pointer to an integer andais an integer, we
may evaluate:


pname = &a;

Declaration and initialization can be combined into one statement:

int * pname = &a;

The following code contained in the filepointer2.ccevaluates four variables and
extracts their memory addresses through pointers:


#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
int a=4;
float b=1.2;
double c=3.45;
char d=99;

int * memada;
float * memadb;
double * memadc;
char * memadd;

memada = &a;
memadb = &b;
memadc = &c;
memadd = &c;

cout << setw(5) << a <<""<<(unsigned int) memada << endl;
cout << setw(5) << b <<""<<(unsigned int) memadb << endl;
cout << setw(5) << c <<""<<(unsigned int) memadc << endl;
cout << setw(5) << d <<""<<(unsigned int) memadd << endl;

return 0;
}
Free download pdf