Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you delete variables in c++?

Tags:

c++

arrays

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

like image 666
fried_rice Avatar asked Dec 02 '10 20:12

fried_rice


2 Answers

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.

like image 128
Kristopher Johnson Avatar answered Oct 04 '22 21:10

Kristopher Johnson


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 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.
like image 34
JaredPar Avatar answered Oct 04 '22 20:10

JaredPar