Chandra Varanasi
Chandra Varanasi

Reputation: 1

Why is my Matrix access function segfaulting?

I don't understand why my member function ij is not able to access the memory locations created in the 2D pointer array rp, which I used in my constructor. Any help is greatly appreciated. Thanks.

Here is my code and its output:


using namespace std;
#include <iostream>
class Mymatrix
{
    int numRows, numCols;
    int **rp;
public:
    Mymatrix(int r, int c)
    {
        numRows = r;
        numCols = c;
        int *rp[numRows];
        int i, j;
        for (i = 0; i < numRows; i++)
            rp[i] = new int[numCols];
        for (i = 0; i < numRows; i++)
        {
            cout << endl;
            for (j = 0; j < numCols; j++)
            {
                *(rp[i] + j) = i + j + 2;
                cout << rp[i] + j << "\t";
                std::cout << *(rp[i] + j) << "\n";
            }
        }
        std::cout << std::endl;
    }
    //Now, define member function to access the element in row-i, column-j.
    int ij(int i, int j)
    {
        cout << *(rp[i] + j) << endl;
        return *(rp[i] + j);
    }
};
///////////////

int main()
{
    Mymatrix M1(5, 7);
    M1.ij(2, 3);
    return 0;
}

////////////////////// Here is the code output /////////////////////

0x2010c20       2
0x2010c24       3
0x2010c28       4
0x2010c2c       5
0x2010c30       6
0x2010c34       7
0x2010c38       8

0x2010c50 3 0x2010c54 4 0x2010c58 5 0x2010c5c 6 0x2010c60 7 0x2010c64 8 0x2010c68 9

0x2010c80 4 0x2010c84 5 0x2010c88 6 0x2010c8c 7 0x2010c90 8 0x2010c94 9 0x2010c98 10

0x2010cb0 5 0x2010cb4 6 0x2010cb8 7 0x2010cbc 8 0x2010cc0 9 0x2010cc4 10 0x2010cc8 11

0x2010ce0 6 0x2010ce4 7 0x2010ce8 8 0x2010cec 9 0x2010cf0 10 0x2010cf4 11 0x2010cf8 12

Segmentation fault

Upvotes: 0

Views: 46

Answers (1)

MasterJEET
MasterJEET

Reputation: 349

You never initialized class member int **rp in your code.

int *rp[numRows]; This is not valid C++ syntax. With luck compiler will create an automatic object which will be unavailable when constructor execution is complete.

rp = new int*[numRows]; Instead do this, it will allocate storage for the class member instead of creating an object local to the constructor.

Upvotes: 1

Related Questions