12.12.2012 Views

Teach Yourself Borland C++ in 14 Days - portal

Teach Yourself Borland C++ in 14 Days - portal

Teach Yourself Borland C++ in 14 Days - portal

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.

Up to Your Neck <strong>in</strong> <strong>C++</strong><br />

Figure 3.1.<br />

A po<strong>in</strong>ter to an object<br />

<strong>in</strong> memory. mail<strong>in</strong>gListRecord*<br />

listArray<br />

Let’s go back to a code snippet you saw earlier:<br />

mail<strong>in</strong>gListRecord* listArray;<br />

listArray = new mail<strong>in</strong>gListRecord;<br />

strcpy(listArray->firstName, “Ian”);<br />

strcpy(listArray->lastName, “Spencer”);<br />

// etc.<br />

On the third l<strong>in</strong>e you see that the firstName data member of the structure is accessed us<strong>in</strong>g<br />

the <strong>in</strong>direct member operator (->) rather than the structure member operator. (We discussed<br />

the structure member operator yesterday <strong>in</strong> the section titled “Structures.” The term direct<br />

member operator is also used and is more representative than structure member operator, so<br />

I will use direct member operator from now on.) When you create an object dynamically, you<br />

must access the object’s data members and functions us<strong>in</strong>g this operator.<br />

Creat<strong>in</strong>g an array of structures dynamically requires a bit more work. Aga<strong>in</strong>, here’s the stackbased<br />

version:<br />

mail<strong>in</strong>gListRecord listArray[3];<br />

listArray[0].zip = 57441;<br />

And the dynamic version:<br />

stack memory<br />

listArray<br />

listArray po<strong>in</strong>ts to<br />

address 0x00780E50,<br />

which is an <strong>in</strong>stance<br />

of the mail<strong>in</strong>gListRecord<br />

structure <strong>in</strong> memory<br />

mail<strong>in</strong>gListRecord* listArray[3];<br />

for (<strong>in</strong>t i=0;izip = 57441;<br />

mail<strong>in</strong>gListRecord<br />

structure <strong>in</strong> memory<br />

heap memory<br />

0x00780E50<br />

firstName<br />

lastName<br />

address<br />

city<br />

state<br />

zip<br />

Note that I have to create a new <strong>in</strong>stance of the structure for each element of the array. Notice<br />

also that to access a data member of the array, I use the <strong>in</strong>direct membership operator<br />

comb<strong>in</strong>ed with the subscript operator.<br />

71<br />

3

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

Saved successfully!

Ooh no, something went wrong!