Skip to main content
gamedev.net
🔒 Locked

Pointer Array Problem

Started by Punx Feb 16, 2003 at 5:49 PM 4 replies 150+ views
Original Post
Punx
Punx
Okay I got it now, thanks. I understand the concept of pointers but it's just putting them into programs that get's me. Need more practice I guess. [edited by - punx on February 16, 2003 7:21:43 PM]
~punx
Miserable
Miserable
You initialise the pointer to point to four newly allocated integers on the heap. These, however, you throw away by making the pointer point to the first element of the statically allocated array (leaking the memory for the first four integers). When you then attempt to delete the data at the pointer, you are trying to deallocate memory on the stack!

There is no need to initialise the pointer to memory created with new if you intend to make it point to something statically allocated, as here. (It may be a good idea to initialise each pointer to 0 if you cannot immediately assign something meaningful to it.)
TravisWells
TravisWells
Ok, you've got two arrays.
array1, and a unnamed array you allocate with new int [4];
Lets call the memory for array1 [int4_A] and the currArray new'd memory [int4_B]

So:

array1->[int4_A]
currArray->[int4_B]

then you fill [int4_A] with numbers
then this line:

currArray = array1;

now it looks like this:

array1->[int4_A]
currArray ->[int4_A]
[int4_B]

So now array1 and currArray both mean the first array.
Nothing points to the second, so you've just leaked that memory.

Then when you call this:
delete [] currArray;
You're trying to delete array1, not the [int4_B]!
Which you can't , since you didn't create that memory with new,
it was created by entering the function (and it will be deleted
when you exit the function).
So just change this:

int *currArray = new int[4];

to:

int *currArray=array1;

Since you're trying to manipulate a static array, there's no reason to allocate more memory.
Then just leave out the

currArray = array1;

line.
It should work fine then.






[edited by - TravisWells on February 16, 2003 7:07:30 PM]
Punx
Punx
Okay thanks it works fine now. But now what if I had another array, array2. After initializing the pointer to array1, how do I make it point to array2?

[edited by - punx on February 16, 2003 7:18:53 PM]
~punx
Xai
Xai
currArray = array2;

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.