Learning about dynamic memory - Question

A

AMT2K5

Hello folks. I am at the chapter in my textbook towards learning about
dynamic memory and am practicing with a few examples and lessons from a
variety of places.

I am confused about one certain function within my practice question,
it reads

"int grow(int s = 10) - a private function that allocates memory to
savings. If savings is NULL allocate enough memory to hold s Accounts.
If savings is not NULL increase by s the size of the array whose
address is stored in savings, do not lose any of the data currently
stored in the array. If the memory allocation succeeds set arraySize to
the size of the array, other wise set arraySize and size to zero.
Return arraySize."

Trying to interpret that code, I have...

int grow(int s = 10) {
// Should I have delete [] savings here?
if(savings = NULL){
savings = new Account [ s ]; }

else{ savings = new Account [ arraySize + s];
// "Whose address is stored in savings? How do I do that?

}

Basically im confused on how to not lose any data by growing the size
of the array.

I'd appreciate any help, thanks in advance.
 
A

Alipha

AMT2K5 said:
Hello folks. I am at the chapter in my textbook towards learning about
dynamic memory and am practicing with a few examples and lessons from a
variety of places.

I am confused about one certain function within my practice question,
it reads

"int grow(int s = 10) - a private function that allocates memory to
savings. If savings is NULL allocate enough memory to hold s Accounts.
If savings is not NULL increase by s the size of the array whose
address is stored in savings, do not lose any of the data currently
stored in the array. If the memory allocation succeeds set arraySize to
the size of the array, other wise set arraySize and size to zero.
Return arraySize."

Trying to interpret that code, I have...

int grow(int s = 10) {
// Should I have delete [] savings here?
if(savings = NULL){

that if statement is always false.
savings = new Account [ s ]; }

else{ savings = new Account [ arraySize + s];
// "Whose address is stored in savings? How do I do that?

}

Basically im confused on how to not lose any data by growing the size
of the array.

allocate a new array, copy the existing elements from the old array to
the new array, then delete[] the old array.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,077
Latest member
SangMoor21

Latest Threads

Top