jeudi 1 février 2018

New to C++: Creating a 2D array and having a correct assignment operator: Segmentation Error

I am new to c++ and I have to create a 2D array using pointers. I have completed the creation of the array but I cannot run anything after the initial creation of the matrix due to a "Segmentation fault". I believe this is from my assignment operator, but I'm not sure. This could be from the copy constructor, but because we have to use pointers I am lost. Any help would be appreciated.

#ifndef My_Matrix_H
#define My_matrix_H
#include "My_matrix.h"
#include <stdexcept>

My_matrix::My_matrix() //contructor
{
n = 0;
m = 0;
ptr = NULL;
}

My_matrix::My_matrix(int n1, int m1) //creation of the matrix
{

ptr = new int*[n1];
for (int i = 0; i < n1; i++)
{
    ptr[i] = new int[m1];
    for (int j = 0; j < m1; j++)
    {
        ptr[i][j] = 0;
    }
}

}

My_matrix::My_matrix(const My_matrix& mat) //copy constructor
{

    n = mat.n;
    m = mat.m;
    ptr = new int*[n];
    for (int i = 0; i < n; i++)
    {
        ptr[i] = new int[m];
        for (int j = 0; j < m; j++)
        {
            ptr[i][j] = mat.ptr[i][j];
        }
    }

}

My_matrix::~My_matrix() //destructor
{
    for (int i = 0; i < n; i++)
    {
        delete[] ptr[i];
    }
    delete[] ptr;
}

My_matrix& My_matrix::operator=(const My_matrix& mat) //assignmemt operator
{

    n = mat.n;
    m = mat.m;
    ptr = new int*[n];
    cout << "1" << endl;
    for (int i = 0; i < n; i++)
    {
        cout << "2" << endl;
        ptr[i] = new int[m];
        for (int j = 0; j < m; j++)
        {
            cout << "3" << endl;
            ptr[i][j] = mat.ptr[i][j];
        }
    }

}

void My_matrix::elemset(int i, int j, int num) //puts stuff into matrix
{
ptr[i][j] = num;
}
}#endif

Aucun commentaire:

Enregistrer un commentaire