How do you delete variables in c++?
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 ...
- Create a child scope and define a new variable of the same name with a different type.
- Switch
list
to anint*
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 your array is allocated on the heap, then:
int *L = new int[10];
delete[] L;
L = new int[9];
There is no concept of "deleting" a local variable declared on the stack.
To delete an array in C++ you'd use the delete[]
operator. See this link.
You'll want to be careful. What you have is a static array. When you use delete
or delete[]
it must be on dynamically allocated variables (ones you made with new
). To do that:
int* list = new int[10];
//...Code...
delete[] list;
list = new int[9];
Don't forget to delete
if you new
! (Ideally you should use something managed so you can't forget, like you said).
Your
int list[10];
is a static one. Arrays that are declared as variables are static objects in C++, and you can't delete/create them... it's a compile time thing.
You need to explicitly declare your array as an array object, say
int *list=new int[10];
Although it still seams a declaration, it's not: the new operand will trigger mem-allocation code)... If you want to allocate more or less space you need to free it first:
delete[] list;
and then use the new operand to make a new on (of the same int
type)
Of course, you could always do this:
{
int list[10];
... 'list' has 10 elements ...
{
int list[9];
... 'list' has 9 elements ... other 'list' inaccessible
}
... 'list' 10 elements ... other 'list' non-existent.
}
Can't imagine why you would though.
精彩评论