C ++ Dynamic Class Distribution of a 2D Array

A very new beginner here, and I am at the end of my rope with this task and will be very grateful for any help :). Sorry in advance for the length.

I am having trouble retrieving and adjusting the values ​​for my dynamically allocated 2D array. I have a class, defined below, which should build a 2D array, after which I need to set the value for a given point in the array, and also get the value at this point.

I started the debugger and realized that I have a segmentation error when the setValue function runs. Can someone help me understand what I am doing wrong? As a beginner, the easier the conditions are better :). Thank you in advance.

#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;
}
+4
1

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

. - . , . -, . :

xtable = new float*[yResolution];

, yResolution xResolution . getValue setValue .

xResolution yResolution , :

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

xRes yRes , :

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

, 3 .

+7

Source: https://habr.com/ru/post/1678926/


All Articles