在C++中的类内部创建的二维动态分配数组

Two-dimensional dynamic allocated arrays created inside a class in C++

本文关键字:二维 动态分配 数组 创建 C++ 内部      更新时间:2023-10-16

我对c++和其他面向对象语言还比较陌生(我已经上了一学期的c课程,现在上的是c++课程)。我在和一个同学一起上课时遇到了制作动态分配的二维数组的问题。

演习本身将是:

准备一个名为"matrix"的类,该类能够存储二维动态分配的数组(用于浮点变量)。记住高度和宽度等信息必须正确存储在某个地方,元素指针也是。

类需要包含允许创建使用以下策略之一的对象:由MxN元素组成的阵列,例如:

Array A (4, 5);

创建一个空数组:

Array B;
The creation of an array that is a copy of another previous one:
Array C (A);  

经过一段时间的努力,我们的代码目前如下:obs:Matriz是我们在语言中调用二维数组的方式。

Matriz.h

#pragma once
class Matriz{
public:
int l, c;
float** matriz;
void setL(int _l);
void setC(int _c);
int getL();
int getC();
Matriz();
Matriz(int _l, int _c);
Matriz(Matriz& m);
float **getMatriz();
float getElement(int pL, int pC);
void setElement(int pL, int pC, float value);
};

Matriz.cpp

#include "Matriz.h"
Matriz::Matriz(){
l = c = 0;
matriz = new float*[l];
for (int i = 0; i<l; i++) {
matriz[l] = new float[c];
}
}
Matriz::Matriz(Matriz& m){
l = m.getL();
c = m.getC();
matriz = new float*[l];
for (int i = 0; i<l; i++) {
matriz[l] = new float[c];
}
for (int i = 0; i<l; i++) {
for (int j = 0; j<l; j++) {
matriz[i][j] = m.matriz[i][j];
}
}
}
Matriz::Matriz(int _l, int _c){
l = _l;
c = _c;
matriz = new float*[l];
for (int i = 0; i<l; i++) {
matriz[l] = new float[c];
}
}
float **Matriz::getMatriz(){
return matriz;
}
int Matriz::getC(){
return c;
}
int Matriz::getL(){
return l;
}
void Matriz::setC(int _c){
c = _c;
}
void Matriz::setL(int _l){
l = _l;
}
float Matriz::getElement(int pL, int pC){
return matriz[pL][pC];
}
void Matriz::setElement(int pL, int pC, float value){
matriz[pL][pC] = value;
}

main.cpp

#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
int l = 2, c = 2;
float **m;
m = new float*[l];
for (int i=0; i<2; i++) {
m[i] = new float[c];
}
Matriz a(2, 2);
a.setC(2);
a.setL(2);
cout << " c = " << a.getC() << " l= " << a.getL() << "n";
for (int i = 0; i<l; i++) {
for (int j = 0; j<c; j++) {
a.setElement(i, j, 0);
cout << " Elemento " << 1 << " " << 1 << " = " << a.getElement(l, c) << "n";
}
}
a.setElement(0, 0, 1); // <- this is just for testing

system("pause");
}

iostream和类头都包含在stdafx.h 中

在MSVS 2013编译它在中断

void Matriz::setElement(int pL, int pC, float value){
matriz[pL][pC] = value;
}

我们真的不确定为什么,调试器给了我"ConsoleApplication15.6exe中0x01092E27处未处理的异常:0xC0000005:写入位置0xCDCDD1的访问冲突。">

然而,我们怀疑数组中的某些内容是错误的,当程序试图将某些内容写入其中的某个元素时,它根本不存在/无法访问,因此无法更改该特定元素的值。

我们感谢任何帮助或建议,随时提出改进或编码建议,学习新东西总是很好的=)。

我认为您的错误实际上就在这里:a.getElement(l, c)。当最大索引应该只有1时,lc是数组的边界,例如2。

另一个严重的缺陷(twsaef指出)是您的构造函数:

for (int i = 0; i<l; i++) {
matriz[l] = new float[c];
}

应该是

for (int i = 0; i<l; i++) {
matriz[i] = new float[c];
}

当我在做的时候,这是多余的:

Matriz a(2, 2);
a.setC(2);
a.setL(2);

因为Matriz的构造函数将为您设置lc

此外,你打算用这个做什么:

float **m;
m = new float*[l];
for (int i=0; i<2; i++) {
m[i] = new float[c];
}

目前,它没有用于任何用途。

然后,正如PaulMcKenzie所指出的,当Matriz实例超出范围时,动态分配的内存会发生什么?

正如Matt McNabb所指出的,如果在调用setC()setL()时需要调整Matriz实例的大小,该怎么办?目前,他们只设置成员变量,对内存不做任何操作。