[英]Helper function to construct 2D arrays
我是否打破了 C++ 编码约定,编写了一个助手 function ,它在main()
之外分配了一个二维数组? 因为我的应用程序需要许多 N 维 arrays 我想确保遵循相同的过程。 一个演示我在做什么的原型:
#include <iostream>
// my helper function which allocates the memory for a 2D int array, then returns its pointer.
// the final version will be templated so I can return arrays of any primitive type.
int** make2DArray(int dim1, int dim2)
{
int** out = new int* [dim1];
for (int i = 0; i < dim2; i++) { out[i] = new int[dim2];}
return out;
}
//helper function to deallocate the 2D array.
void destroy2DArray(int** name, int dim1, int dim2)
{
for (int i = 0; i < dim2; i++) { delete[] name[i]; }
delete[] name;
return;
}
int main()
{
int** test = make2DArray(2,2); //makes a 2x2 array and stores its pointer in test.
//set the values to show setting works
test[0][0] = 5;
test[0][1] = 2;
test[1][0] = 1;
test[1][1] = -5;
// print the array values to show accessing works
printf("array test is test[0][0] = %d, test[0][1] = %d, test[1][0] = %d, test[1][1] = %d",
test[0][0],test[0][1],test[1][0],test[1][1]);
//deallocate the memory held by test
destroy2DArray(test,2,2);
return 0;
}
我担心这可能不是内存安全的,因为似乎我在使用它的 function 之外分配了 memory(潜在的超出范围的错误)。 当我制作一个小数组时,我可以读取和写入数组,但是当我扩大它并且代码上有许多操作可能会访问和更改这些值时,我会担心。
我可以通过创建一个包含这些函数作为成员的数组 class 来回避这些问题,但我对此感到好奇,因为它是 C++ 样式和范围的边缘案例。
像这样分配 2D arrays 与根据您的语句声明像int ary[10][10]
这样的局部变量时得到的结果是有区别的
我担心此操作可能不是内存安全的,因为似乎我正在为使用它的 function 之外的数组分配 memory(潜在的范围外错误)
我猜你还没有完全理解。
您正在堆上分配 arrays。 声明像int ary[10][10]
这样的局部变量会将其放在堆栈上。 在后一种情况下,您需要担心在其基于范围的生命周期之外不引用 memory; 也就是说,以下是完全错误的:
//DON'T DO THIS.
template<size_t M, size_t N>
int* make2DArray( ) {
int ary[M][N];
return reinterpret_cast<int*>(ary);
}
int main()
{
auto foo = make2DArray<10, 10>();
}
因为ary
对于 function 是本地的,并且当调用make2DArray<10,10>
创建的堆栈帧消失时, function 返回的指针将悬空。
堆分配是另一回事。 它比词汇 scope 的寿命更长。 它一直持续到它被删除。
但无论如何,正如其他人在评论中所说,您的代码看起来像 C 而不是 C++。 更喜欢std::vector<std::vector<int>>
而不是自己滚动。
如果您必须使用数组并且对std::vector
过敏,请创建二维数组(矩阵)作为 memory 中的一个连续区域:
int * matrix = new int [dim1 * dim2];
如果要将值设置为零:
std::fill(matrix, (matrix + (dim1 * dim2)), 0);
如果要访问<row, column>
的值:
int value = matrix[(row * column) + column];
由于矩阵是一个分配,你只需要一个delete
:
delete [] matrix;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.