How do you delete variables in a c++ program? i have a simple int list[10];
and i want delete it and change it to int list[9]
. i would use vectors, but i still want to know how to do it
If you have something declared like this:
int list[10];
there is no way to "delete" it. It is either a global variable, with statically allocated storage, or it is a local variable with storage on the stack.
I don't know exactly what you are trying to accomplish, but maybe something like this will help you figure it out:
int *list = new int[10]; // allocate a new array of 10 ints
delete [] list; // deallocate that array
list = new int[9]; // allocate new array with 9 ints
As you suggest in your question, you will almost always be better off using std::vector
, std::list
, and the like rather than using raw C-style arrays.
This is not called deleting a variable but instead redefining the type of a variable. This is simply not possible in C++. Once a variable type has been established it cannot be changed.
There are several ways to emulate or work around this behavior ...
list
to an int*
and allocate it's memory on the heap. This will have the effect of redefining it to a different size without changing it's type.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With