与二维数组的内存问题 [英] Memory issues with two dimensional array
本文介绍了与二维数组的内存问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
继这个很好的例子我发现,我试图创建一个函数,动态生成的 INT
值的2D网格(二维数组)。
它的工作原理相当不错的第一对夫妇您变更值时间,但如果经过崩溃了。我想,其中内存被释放,因为它应该不起作用的部分。
无效testApp :: generate2DGrid(){
INT I,J = 0;
//删除previous二维数组
//(发生在为cols和rows previous值为0)
如果((numRows行preV = 0)及!及(numColumns列preV = 0)!){
对于(i = 0; I< numRows行preV;我++){
删除[] Arr2D [I]
}
}
//创建一个二维数组
Arr2D =新INT * [为numColumns]
对于(i = 0; I<为numColumns;我++){
Arr2D [我] =新的INT [numRows行]
}
//指定一个随机值
对于(i = 0; I< numRows行;我++){
为(J = 0; J<为numColumns; J ++){
Arr2D [I] [j]的= ofRandom(0,10);
}
}
//更新previous值与新
numRows行preV = numRows行;
为numColumns $ P $ = PV numColumns列;
}
解决方案
2维数组在C ++中,没有内存问题:
的#include<载体>
类型定义的std ::矢量< INT>阵列;
类型定义的std ::矢量<数组> TwoDArray;
用法:
TwoDArray Arr2D;
//添加行
的for(int i = 0; I< numRows行++我){
Arr2D.push_back(阵列());
}
//测试数据填写
的for(int i = 0; I< numRows行;我++){
对于(INT J = 0; J<数numCols; J ++){
Arr2D [I] .push_back(ofRandom(0,10));
}
}
//确保数据是存在的
的for(int i = 0; I< numRows行;我++){
对于(INT J = 0; J<数numCols; J ++){
性病::法院<< Arr2D [I] [J]<< '';
}
性病::法院<< '\ N';
}
Following this nice example I found, I was trying to create a function that dynamically generates a 2D grid (two dimensional array) of int
values.
It works fairly well the first couple of times you change the values but if crashes after that. I guess the part where memory is freed doesn't work as it should.
void testApp::generate2DGrid() {
int i, j = 0;
// Delete previous 2D array
// (happens when previous value for cols and rows is 0)
if((numRowsPrev != 0) && (numColumnsPrev != 0)) {
for (i = 0; i < numRowsPrev; i++) {
delete [ ] Arr2D[i];
}
}
// Create a 2D array
Arr2D = new int * [numColumns];
for (i = 0; i < numColumns; i++) {
Arr2D[i] = new int[numRows];
}
// Assign a random values
for (i=0; i<numRows; i++) {
for (j = 0; j < numColumns; j++) {
Arr2D[i][j] = ofRandom(0, 10);
}
}
// Update previous value with new one
numRowsPrev = numRows;
numColumnsPrev = numColumns;
}
解决方案
2-dim array in C++ with no memory issues:
#include <vector>
typedef std::vector<int> Array;
typedef std::vector<Array> TwoDArray;
Usage:
TwoDArray Arr2D;
// Add rows
for (int i = 0; i < numRows; ++i) {
Arr2D.push_back(Array());
}
// Fill in test data
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
Arr2D[i].push_back(ofRandom(0, 10));
}
}
// Make sure the data is there
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
std::cout << Arr2D[i][j] << ' ';
}
std::cout << '\n';
}
这篇关于与二维数组的内存问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文