22.08.2013 Views

Pointers and Dynamic Arrays

Pointers and Dynamic Arrays

Pointers and Dynamic Arrays

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Display 10.1 Uses of the Assignment Operator with Pointer Variables<br />

p1 = p2;<br />

p1<br />

p2<br />

*p1 = *p2;<br />

p1<br />

p2<br />

Pointer Variables Used with =<br />

If p1 <strong>and</strong> p2 are pointer variables, then the statement<br />

p1 = p2;<br />

<strong>Pointers</strong> 409<br />

changes the value of p1 so that it is the memory address (pointer) in p2. A common way to think<br />

of this is that the assignment will change p1 so that it points to the same thing to which p2 is currently<br />

pointing.<br />

address, we have merely indicated the address with an arrow that points to the variable<br />

with that address.<br />

Since a pointer can be used to refer to a variable, your program can manipulate variables<br />

even if the variables have no identifiers to name them. The operator new can be<br />

used to create variables that have no identifiers to serve as their names. These nameless<br />

variables are referred to via pointers. For example, the following creates a new variable<br />

of type int <strong>and</strong> sets the pointer variable p1 equal to the address of this new variable<br />

(that is, p1 points to this new, nameless variable):<br />

p1 = new int;<br />

Before: After:<br />

Before:<br />

8<br />

9<br />

8<br />

9<br />

This new, nameless variable can be referred to as *p1 (that is, as the variable pointed to<br />

by p1). You can do anything with this nameless variable that you can do with any other<br />

p1<br />

p2<br />

p1<br />

p2<br />

After:<br />

8<br />

9<br />

9<br />

9<br />

new

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!