We firstly set up a pointer:
int *intpointer;
... then dynamically allocate memory with new.
intpointer = new int;
new is a type safe operation, it returns a pointer to the type given, int in this case.
That pointer points to an object of the specified type, here an int, with the amount of memory required being automatically determined on the basis of the operand type.
If we use new we need to use delete to release the memory.
delete intpointer;
If we don’t we get a memory leak.
Variables can be default initialised, with the default value type and sometimes location dependent.
Built-in types defined outside function bodies are initialised to zero, those within are uninitialized, effectively having an undefined value.
We can also initialise the variables ourselves when we set up the memory,
int *p = new int(5);
The type specifier auto can come in useful again.
Consider the following:
int *p;
p = new int(5);
cout << p << endl;
// delete p;
There will be a memory leak.
To create a dynamic array we can use the new[] operator.
int *intVar;
intVar = new int[100]; // dynamic array
for(int i = 0; i < 100; ++i)
intVar[i] = 25-i; // initialize the array
delete [] intVar; // frees the allocated array
You have to be careful if you have something like a pointer to an array of pointers, ...
Person **p = new Person* [2];
p[0] = new Person("Peter");
p[1] = new Person("Alex");
Using delete[] p; just causes the p pointer to be released, not the actual objects themselves. You could step through the different index values and use delete p[index] on each. Or, as will probably be discussed later, you could use a wrapper class.
float **fVar;
fVar = new float* [10]; // allocate pointer array, 10 float pointers
for(int i = 0; i < 10; ++i)
fVar[i] = new float[10]; // allocate memory to each
. . . .
. . . .
for(int i = 0; i < 10; ++i)
delete [] fVar[i];
delete [] fVar;