Deleting Variables


Variables that you create with new also have to be destroyed when you're done using them. To do this, you say "delete" and then the name of the pointer. (Or, if you created an array, you use "delete[]" and then the name of the pointer to the array) For instance:

int *burrito;
int *enchilada;

burrito = new int[3];
enchilada = new int;

burrito[0] = 4;
burrito[1] = 8;
burrito[2] = 12;

delete enchilada;
delete[] burrito;

Seem easy enough, right? Remember that delete works just like free did in Pascal -- The contents pointed to are removed, but not the pointer. You can create more variables and give their location to the same pointer, if you want.

You probably noticed that the code created a pointer to "int[3]", and then started using burrito as though it was an array. How can this be? Well, first a quick explanation of what an array really is. Say you create an array of ten integers using the declaration "int salsa[10];". Inside your computer's memory, the program makes a location big enough to hold ten integers, and gives the variable "salsa" the location of the first one. When you say "salsa[5]", it's taking the location of the first part and looking 5 locations ahead. Don't worry if that's a little confusing. The important part is that you know that if you want to create arrays using new, you can. In fact, the whole purpose of new, really, is to create arrays whose size can be determined while the program is running!


Table of Contents

Pointers | Pointer Operations | More Pointer Issues | Deleting Variables
Checking for Nothing | Exercises