cs.boisestate.edu

Download Report

Transcript cs.boisestate.edu

Dynamically Allocated Arrays
December 4, 2013
Skip the Rest of this
PowerPoint
Next Time

Read Chapter 8,pp. 351-357
Intro to Pointers


A pointer is a variable that holds an address
Declaration uses *
int* p;
int i;

& is “Address of” operator. Gets the address
of a variable.
p = &i;
Intro to Pointers

* is used to dereference a pointer:
*p = 15;


Above: what p points to is assigned the
value, 15.
pointers.cpp
Arrays Are Pointers

In a program, an array, a, and a pointer, p,
are the same kind of pointer.
int* p; //p is an int pointer
int a[10];

They both point at an int.
Arrays Are Pointers

p can get the address that a is pointing at.
p = a;

It is illegal to change a.
a = p;


Once p is assigned the value of a it can be
used like an array variable.
arrayPtr.cpp
Dynamically Allocated Arrays

Sometimes the amount of memory needed by an
array can vary greatly.


e.g. Number of campers in Ponderosa park in January
vs. August.
To save memory, use dynamic array.
Dynamically Allocated Arrays



Declare using a pointer
Can return to memory
Can vary size
//allocate array with 20 ints
int *pt = new int[20];
Initialize Array
double *buff = new double[10];
for (int i=0; i<10; i++)
{
*buff = 100.0;
buff++;
}
Initialize Array Alternative
double *buff = new double[10];
for (int i=0; i<10; i++)
{
buff[i] = 100.0;
}
Release memory
delete []pt;
delete []buff;

If an array is no longer needed this can free
up memory for other programs.
Another Example
int* p = new int[10];
for (int i = 0; i< 10; i++)
{
p[i] = i * i;
}
cout << *p << " " << *(p+1)
<< " " << p[2] << endl;
NULL

Can assign a pointer to a NULL value, which
is pointing to nothing.
Memory Leak
void myfunction( ){
int *pt;
pt = new int[100];
.
.
//no delete
}
//in main:
while(cond.)
myfunction();
Destructors

Return data memory


When object goes out of scope.
Look at messageDest.cpp
Copying Objects with Dynamic
Arrays(Skip)

Assignment Operator copies objects



message2 = message;
Copies a pointer, not the array
Example in message.cpp

Messy error.
Copying Objects with Dynamic
Arrays(Skip)

Deep Copying


Create a new array and copy contents to the
array
messageFixed.cpp

copyFrom function fixes
Overload ==(Skip)


To make sure no problems happen, overload
==
Do deep copy when an assignment is done.
Copy Constructor(Skip)

Copying of objects occur:





Passing a copy of an argument using pass-byvalue.
Returning an object from a function:
return msg1;
By default these are shallow copying.
Better to provide a copy constructor that does
a deep copy.
messageCopyConstr.cpp
Copy Constructor


Odd things can happen without copy
constructor.
If two objects point to same array, something
done to one object effects the other.

Like the problem with message