Programming and Graphics

(Kiana) #1

5.1 Pointers to scalars and characters 131


Two ways of changing a variable


We can change the value of variable either directly or indirectly by chang-
ing the content of its memory address. The direct route amounts to telling a
friend, “I will send you a gift”; the indirect way amounts to saying, “I will send
a gift to the occupant of your house.”


The indirect way is illustrated in the following code contained in the file
pointer3.cc:


#include <iostream>
using namespace std;

int main()
{
double a = 3.4;
cout << a << " ";

double * memada = &a;
*memada = 3.5;
cout << a << endl;

return 0;
}

Running the code prints on the screen:


3.4 3.5

Null pointer


A declared but non-initialized pointer has an arbitrary and possibly in-
appropriate value leftover in the memory block where it resides. To ensure a
proper value, we initialized the pointer as NULL by stating, for example,


int * pnt1 = NULL;

Pointer arithmetic


When we increase or decrease the value of a pointer by one unit, we
obtain the memory address of a memory cell that is shifted to the right or left
by a number of memory cells corresponding to the byte size of the stored data
type.


The following code illustrates the memory layout of a two-dimensional
array (matrix):

Free download pdf