You can allocate in a fairly traditional manner for a given number of pointers
and and then a given number of float
assigning a pointer to each allocated block of float
using the new expression and then using a corresponding delete expression to regain the memory allocated to avoid a memory leak when that allocated memory is no longer needed. It is loosely analogous to using malloc
and free
, but there is a large difference in what goes on under the hood.
For example, given your pointer-to-pointer-to-float, you could construct a short example to illustrate:
#include <iostream>
#include <iomanip>
using namespace std;
#define ROWS 10
#define COLS 10
int main (void) {
float **array = NULL; /* pointer to pointer to float */
array = new float*[ROWS]; /* allocate ROWS pointers to float */
for (int i = 0; i < ROWS; i++) {
array[i] = new float[COLS]; /* allocate COLS floats */
for (int j = 0; j < COLS; j++)
array[i][j] = (i + 1) * (j + 1);
}
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++)
cout << setw(4) << array[i][j];
cout << "\n";
delete[] array[i]; /* delete COLS floats */
}
delete[] array; /* delete ROWS pointers to float */
}
Example Use/Output
$ ./bin/array_new_del
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
You must take care to always preserve a pointer to the memory you allocate and to delete
the memory you allocate when it is no longer needed to prevent leaking memory. It is also imperative that you run your code that allocates and deletes memory through a memory error checking program to insure you have used the memory correctly and that all memory has been freed when it is no longer needed. For Linux, valgrind
is the normal choice. All you need to it is run your code through it, e.g.
$ valgrind ./bin/array_new_del
==1206== Memcheck, a memory error detector
==1206== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==1206== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==1206== Command: ./bin/array_new_del
==1206==
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
==1206==
==1206== HEAP SUMMARY:
==1206== in use at exit: 0 bytes in 0 blocks
==1206== total heap usage: 13 allocs, 13 frees, 74,208 bytes allocated
==1206==
==1206== All heap blocks were freed -- no leaks are possible
==1206==
==1206== For counts of detected and suppressed errors, rerun with: -v
==1206== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
Always verify that you have freed all memory you allocate and that there are no memory errors.