Programming and Graphics

(Kiana) #1

Pointers^5


C++ offers an arsenal of tools that allow us to access the inner workings of a
code and directly manipulate and allocate memory. Among these tools, pointers
play a prominent role. Pointers are both revered and feared for their possible
misuse.


A pointer is the identification number of a variable or function, assigned
by the CPU on execution. A pointer can be used to identify a variable in
the memory bank, reserve space for new data, and erase unwanted data to
eliminate memory leaks. The implementation of pointers can be simple or
subtle depending on the data types considered.


5.1 Pointers to scalars and characters..................


As soon as a scalar variable is declared in the main program or in a function,
it is given a memory address. The content of the memory address is the value
of the variable, which may change during execution. If the variable occupies
more than one byte, the memory address of the variable is the memory address
of the first byte.


Reference operator


We can extract the memory address of a variable using thereference
operator, &, which should be read as: “memory address of variable ...”; the
name of the appended variable should replace the three dots.


The following code continued in the filepointer1.ccevaluates four vari-
ables and extracts their memory addresses:


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

int main()
{
int a=4;
Free download pdf