Pewds
Pewds

Reputation: 65

How to create 2D array matrix using basic loop

Currently I'm trying to create a sparse matrix with this declaration:

typedef int Data;

struct Element 
{
    int i;
    int j;
    Data value;
};

I'm allowing user to input number of row they want:

int size;

cout << "Enter the number of element: ";
cin >> size;

// Function to construct sparse matrix
constructSparseMatrix(size,3);

My try for constructSparseMatrix function:

void constructSparseMatrix(int row, int col) {
    int** arr = new int*[row];
    for(int i = 1; i <= row; i++) {
        arr[i] = new int[col];
        cout << arr[row][col];
    }

}

But when I input any number then the application output nothing but stop working. My expected output look something like this if I input 2:

Insert (1 ,2, 3)
Insert (4, 5, 6)

Can someone point me in the correct direction? Maybe this is easy but I'm kinda new to C++ so please bear with my ignorance.

Upvotes: 1

Views: 7520

Answers (1)

Shoe
Shoe

Reputation: 76260

The segmentation fault you are receiving is caused by this line:

cout << arr[row][col];

In that context, row and col are the dimensions of the matrix, therefore the elements go from 0 to row - 1 and from 0 to col - 1. When you access arr[row][col] you accessing elements out of bounds.

Not to mention that your for loop also goes out of bounds:

for(int i = 1; i <= row; i++) {

and will start from 1 instead of 0.

A correct function would look more like:

int** constructSparseMatrix(int row, int col) {
    int** arr = new int*[row];
    for(int i = 0; i < row; i++) {
        arr[i] = new int[col];
        for (int k = 0; k < col; k++)
            arr[i][k] = /* initialize element (i, k) */;
    }
    return arr;
}

Live demo

Finally, I'd recommend a good book on C++. It's clear that you are missing a lot of the basics of C++. new and delete are highly advanced topics. I'd recommend starting with std::array, std::vector and std::map instead.


Sparse matrices are often not implemented with an actual matrix (array) of NxM elements; that is used for dense matrices (where most of the elements are different from 0).

A possible implementation is with an std::map<std::pair<int, int>, element>, where you map 2D indeces to a specific element. For other possible implementations look at this page.

An easier alternative it to use Boost.uBLAS which provides various kind of matrices.

Upvotes: 1

Related Questions