[英]Declaring multidimensional floating or unsigned dynamic array in C++
如何在C ++中初始化一个浮动或无符号的多维动态数组?
我尝试了以下操作并遇到了段错误,
float **array = NULL:
array = new float* [rows];
for(unsigned int i = 0; i < rows; ++i)
{
array[i] = new float [cols];
}
提前致谢。
我投票关闭了它,方法是声明一个指向多维数组的指针并分配该数组的副本。
声明多维数组arrary[col][rows]
, [col]
必须为常数,而不必[rows]
为常数。 此符号应该可以解决问题。
const int col = someval;
const int row = someval;
int (*array)[row] = new int[col][row];
否则,您可以使用single
维度数组,使其具有[row*col]
元素。 从那里开始,为2D structure
的平面数组编制indexing
时必须进行计算。
通常,单个数组和两个用于循环的数组如下所示:
type *array = new type[row * col];
for ( int i = 0; i < row; i++ ) {
for ( int j = 0; j < col; j++ ) {
array[i * col + j];
}
}
这应该有所帮助。
可以在一个相当传统的方式分配用于给定数量的pointers
和,然后在给定数量的float
分配指针的每个所分配的块float
使用新表达 ,然后使用相应的删除表达式重新获得分配,以避免一个存储器当不再需要分配的内存时发生内存泄漏 。 它大致类似于使用malloc
和free
,但是在malloc
有很大的不同。
例如,给定您的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)
始终确认已释放所有分配的内存,并且没有内存错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.