繁体   English   中英

c++ 二维数组类的动态分配

[英]c++ Dynamic Allocation of 2D Array Class

这里是一个非常新的初学者,我已经完成了这项任务,非常感谢任何帮助:)。 提前道歉。

我在检索和设置动态分配的二维数组的值时遇到了一些麻烦。 我有一个类,定义如下,它应该构造一个二维数组,此时我需要选择将值设置为数组中的给定点并检索给定点的值。

我运行了调试器,并在 setValue 函数运行时发现我有一个分段错误。 谁能帮我理解我做错了什么? 作为初学者,术语越简单越好:)。 提前谢谢你。

#include <iostream>
using namespace std;


class array2D
{
    protected:
        int xRes;
        int yRes;
        float ** xtable;

    public:
        array2D (int xResolution, int yResolution);
        ~array2D() {}
        void getSize(int &xResolution, int &yResolution);
        void setValue(int x,int y,float val);
        float getValue(int x,int y);
};


array2D::array2D(int xResolution, int yResolution)
{
    xRes=xResolution;
    yRes=yResolution;

    float ** xtable = new float*[yResolution];

    for(int i=0;i < yResolution;i++)
    {
        xtable[i] = new float[xResolution];
    }

    for(int i=0;i < yRes;i++)
    {
        for(int j=0;j < xRes;j++)
        {
            xtable[i][j]=45;
        }
    }
}

void array2D::getSize(int &xResolution, int &yResolution)
{
    xResolution=xRes;
    yResolution=yRes;
    cout << "Size of Array: " << xResolution << ", " << yResolution << endl;
}

void array2D::setValue(int x,int y,float val)
{
    xtable[x][y] = val;
}

float array2D::getValue(int x,int y)
{
    return xtable[x][y];
}

int main()
{
    array2D *a = new array2D(320,240);
    int xRes, yRes;
    a->getSize(xRes,yRes);
    for(int i=0;i < yRes;i++)
    {
        for(int j=0;j < xRes;j++)
        {
            a->setValue(i,j,100.0);
        }
    }

    for(int i=0;i < yRes;i++)
    {
        for(int j=0;j < xRes;j++)
        {
            cout << a->getValue(i,j) << " ";
        }

        cout << endl;
    }

    delete[] a;
}

线

float ** xtable = new float*[yResolution];

创建一个函数局部变量。 类的成员变量仍然未初始化。 那不是你想要的。 要分配内存并将其分配给成员变量,请从该行中删除类型说明符。 只需使用:

xtable = new float*[yResolution];

此外,您还需要切换使用yResolutionxResolution在这些线路。 否则, getValuesetValue将错误地使用索引。

互换使用xResolutionyResolution在下面,这样你使用:

float ** xtable = new float*[xResolution];
for(int i=0;i < xResolution;i++)
{
    xtable[i] = new float[yResolution];
}

在以下几行中交换xResyRes的使用,以便您使用:

for(int i=0;i < xRes;i++)
{
    for(int j=0;j < yRes;j++)
    {
        xtable[i][j]=45;
    }
}

由于您的类使用动态内存分配获取资源,因此您应该阅读“三定律”并相应地更新您的类。

int r,c;
cin>>r>>c;
int** p=new int*[r];
for(int i=0;i<r;i++) {
    p[i]=new int[c];
}
for(int i=0;i<r;i++) {
delete [] p[i]; 
}
delete [] p;

使用此代码,您可以在 C++ 中创建一个 2D 动态数组,它将在堆内存中分配此数组的内存。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM