简体   繁体   中英

Understanding C++ Pointers and Memory Allocation

Right now I have a pointer like this:

int * modes = new int[1000];

I want to make it so when I check a condition I can delete the contents of it and make it empty again to add new contents. I can't use vectors or whatever the c++ equivalent of an ArrayList is.

Currently to do this I have:

delete [] modes;
modes = new int[1000];

What I'm thinking is that the first line deletes the memory from the array (the elements it held?) and the second line points to new memory I can use. Is this how pointers work? Or can I no longer use the modes variable since I deleted it?

Also I can't just make a new pointer because this occurs in a for-loop so it would not be in scope right? (I want to access modes pointer from outside for-loop after it ends)

Basically, how do I delete the contents of the pointer array but still stay able to use it as if it was just created?

EDIT: Just wanted to say my program seems like it does work, but I just want to know if I could be causing memory issues and if there's a better way (specifically with pointer array).

As jkb mentioned in his comment, using raw pointers and new/delete directly is discouraged. Other than that you have to keep in mind that at the end of your program, the memory you dynamically allocated has to be freed with "delete", or else you will cause a memory leak.

As for improving your code, I highly recommend reading what dynamic memory is. Also, you should look into why it is important to avoid using so-called "naked" new and delete calls, and the alternative to using them here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM