tmighty
tmighty

Reputation: 11399

C++: Access violation

I am creating a matrix, then I want to fill its values with 0.

I am getting an access violation error in this line:

mat1[x][y]=0;

But I don't see why.

This is my code:

vector<float>getJenksBreaks(vector<float>uFloats,const unsigned int uNumClass)
{

    float* first(&uFloats[0]);
    float* last(first + uFloats.size());
    std::sort(first, last);

    float **mat1 = new float*[uFloats.size()];
    for (int i = 0; i < uFloats.size(); ++i) 
    {
        mat1[i] = new float[uNumClass+1];
    }
    for (unsigned long x=0;x<uNumClass+1;x++)
    {
        for (unsigned long y=0;y<uFloats.size();y++)
        {
            mat1[x][y]=0;
        }
    }

Does anybody see my error?

Thank you.

Upvotes: 0

Views: 345

Answers (2)

Zac Howland
Zac Howland

Reputation: 15872

Instead of dealing with dynamic memory manually:

vector<float> getJenksBreaks(vector<float> uFloats, const unsigned int uNumClass)
{
    std::sort(uFloats.begin(), uFloats.end());

    std::vector<std::vector<float>> mat(uFloats.size());
    std::for_each(mat.begin(), mat.end() [&](std::vector<float>& v)
    {
        v.resize(uNumClass);
    });

    // ...
}

Or (even better) ...

vector<float> getJenksBreaks(vector<float> uFloats, const unsigned int uNumClass)
{
    std::sort(uFloats.begin(), uFloats.end());

    std::vector<std::vector<float>> mat(uFloats.size(), std::vector<float>(uNumClass));

    // ...
}

Which will do exactly what you did without the need to worry about proper placement of your indexes, and is much less prone to errors.

Finally, you can simply create a simple Matrix wrapper class:

class Matrix
{
public:
    Matrix(std::size_t rows, std::size_t cols) : _matrix(rows, std::vector<float>(cols))
    {

    }

    // other matrix functions

private:
    std::vector<std::vector<float>> _matrix;
};

Which would then turn your code into

vector<float> getJenksBreaks(vector<float> uFloats, const unsigned int uNumClass)
{
    std::sort(uFloats.begin(), uFloats.end());
    Matrix matrix(uFloats.size(), uNumClass);

    // ...
}

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310990

Change these loops

for (unsigned long x=0;x<uNumClass+1;x++)
{
    for (unsigned long y=0;y<uFloats.size();y++)
    {
        mat1[x][y]=0;
    }
}

to

for (unsigned long x=0;x<uFloats.size();x++)
{
    for (unsigned long y=0;y<uNumClass+1;y++)
    {
        mat1[x][y]=0;
    }
}

Upvotes: 1

Related Questions