By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,406 Members | 905 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,406 IT Pros & Developers. It's quick & easy.

Pointer Array Question

P: 11

I was wondering if I can do the following without creating memory problems:

Create something like -- int * array1 -- as a public member my class

then initiate it with a new value every time I run a certain function, like this --- array1 = new int[somenumber] ---

but ONLY delete it in the destructor --- delete [] array1 ---

If I reinitiate it with a new value before deleting it, what happens to the old memory which it occupies? Also, can I call ---- array1 = NULL --- or does that not work for arrays?

Thanks a lot,
Feb 19 '07 #1
Share this Question
Share on Google+
3 Replies

Expert 2.5K+
P: 3,652
If you allocate new memory for the pointer, then whatever memory it used to point to still exists. This isn't a major problem in small programs, but it is not a practice you should make a habit of. You should always use the delete command to deallocate that memory, or you may run out of memory in larger applications.

Setting the pointer to NULL will create the same problem. You are changing the location to which the pointer points (in effect, pointing it to nothing), but the data and memory allocated is still embedded in memory.

If you want to create new data for the same pointer in different functions, make sure you delete the old content before creating new content. If you cannot use delete, consider using an alternate method of having multiple arrays of data.
Feb 19 '07 #2

P: 11
Thanks a lot Ganon, that really clears things up.

Does the same thing apply for char strings... i.e. if you initiate a char array (unsigned char *b). Do you deallocate the string like an array (delete []b) or like a single pointer (delete b).

Feb 20 '07 #3

Expert 2.5K+
P: 3,652
I haven't done a lot with character arrays per se, but I imagine they're just like all other pointer arrays - you should use delete [] b.
Feb 20 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.