Home > Blockchain >  Segmentation Fault in dynamically array creation
Segmentation Fault in dynamically array creation

Time:10-22

I was making a cpp program in which it takes two input from the user which determine the size of the 2d array and pass the values to the mat class constructor and dynamically create an array of the user's defined size. But, I don't know why it is not working and showing segmentation fault

#include<iostream>
using namespace std;

class mat{
    int **a;
    int r, c;
    public:
        mat(int row, int col){
            r = row;
            c = col;
            
            for(int i = 0; i < r; i  ){
                *a = new int[r];
                *a  ;
            }
            
        }
        void input(){
            for(int i = 0; i < r; i  ){
                for(int j = 0; i < c; j  ){
                    cin >> a[i][j];
                }
            }
        }
        void display(){
            for(int i = 0; i < r; i  ){
                for(int j = 0; i < c; j  ){
                    cout << a[i][j] << "\t";
                }
                cout << endl;
            }
        }
    
};

int main()
{
    int r, c;
    cout << "enter row :";
    cin >> r;
    cout << "enter column :";
    cin >> c;
    mat m(r, c);
    m.input();
    cout << "array \n";
    m.display();
}

I can feel that the issue is with the for loop in the constructor or maybe I am doing it wrong.

CodePudding user response:

The class contains several errors.

  • The variable a is never initialized. When we try to address the memory pointed to by a we get a segmentation fault. We can initialize it like this a = new int*[r]
  • We should not change where a point's to, so don't use a . Otherwise a[i][j] will not refer to the i'th row and the j'th column. We would also want to release the memory at some point.
  • The inner loop for the columns for(int j = 0; i < c; j ) once entered will never terminate and will eventually produce a segmentation fault. We need to change i < c to j < c.

If we fix these errors, it looks like this:

class mat {
    int** a;
    int r, c;
public:
    mat(int row, int col) {
        r = row;
        c = col;

        a = new int*[r];
        for (int i = 0; i < r; i  ) {
            a[i] = new int[c];
        }
    }
    void input() {
        for (int i = 0; i < r; i  ) {
            for (int j = 0; j < c; j  ) {
                cin >> a[i][j];
            }
        }
    }
    void display() {
        for (int i = 0; i < r; i  ) {
            for (int j = 0; j < c; j  ) {
                cout << a[i][j] << "\t";
            }
            cout << endl;
        }
    }
};
  •  Tags:  
  • c
  • Related