您可以以相当传统的方式为给定数量的pointers 分配一个给定数量的float,然后使用new expression 为float 的每个分配块分配一个指针,然后使用相应的delete expression 在不再需要分配的内存时重新获得分配的内存以避免内存泄漏。这与使用 malloc 和 free 大致相似,但在底层发生的事情有很大的不同。
例如,给定您的 pointer-to-pointer-to-float,您可以构建一个简短的示例来说明:
#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 */
}
使用/输出示例
$ ./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
您必须注意始终保留指向您分配的内存和delete 当不再需要时分配的内存的指针,以防止内存泄漏。您还必须通过内存错误检查程序运行分配和删除内存的代码,以确保您已正确使用内存,并且在不再需要时已释放所有内存。对于 Linux,valgrind 是正常选择。你只需要通过它运行你的代码,例如
$ 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)
始终确认您已释放所有分配的内存并且没有内存错误。