1

Ando poco frustrado porque no comprendo el porque esta función pone basura en vez del resultado. Alguien por favor podría decirme ¿en que me estoy equivocando?

Uso el compilador MinGW 5 que viene en Qt. Aquí les pongo los headers...

class matrix
{
    int **array, rows, columns;
public:
    //constructors that allocates memory and fills the array with 0's
    matrix();
    matrix(int side);
    matrix(int width, int height);

    int getRows() { return rows; }
    int getColumns() { return columns; }
    int getMatrix(); //returns the array atrib

    matrix operator+(const matrix &o);
    matrix operator-(const matrix &o);
    matrix operator*(const matrix &o);
    //set matrix methods write input data to the array
    void setMatrix();
    void setMatrix(int side);
    void setMatrix(int width, int height);
    void setRows(int num) { rows = num; }
    void setColumns(int num) { columns = num; }
    void print();

    ~matrix();
};

Voy a poner la implementación para aclarar todo

#include "matrix.h"
#include <iostream>

//default constructor without parameters.
matrix::matrix()
{
    //for allocating memory since our array is a pointer.
    rows = columns = 3;
    array = new int*[rows];

    for (int i = 0; i < rows; i++) {
        array[i] = new int[columns];
    }

    //just for making sure we don't have garbaje.
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            array[i][j] = 0;
        }
    }
}

//default constructor for square matrices.
matrix::matrix(int side)
{
    //for allocating memory since our array is a pointer.
    rows = columns = side;
    array = new int*[rows];

    for (int i = 0; i < rows; i++) {
        array[i] = new int[columns];
    }

    //just for making sure we don't have garbaje.
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            array[i][j] = 0;
        }
    }
}

//default constructor for defining the rows and columns.
matrix::matrix(int width, int height)
{
    //for allocating memory since our array is a pointer.
    rows = width, columns = height;
    array = new int*[rows];

    for (int i = 0; i < rows; i++) {
        array[i] = new int[columns];
    }

    //just for making sure we don't have garbaje.
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            array[i][j] = 0;
        }
    }
}

//returns a copy of the array pointer.
int matrix::getMatrix()
{
    int **copy = new int*[rows];

    for (int i = 0; i < rows; i++) {
        copy[i] = new int[columns];
    }

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            copy[i][j] = 0;
        }
    }

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            copy[i][j] = array[i][j];
        }
    }
    return **copy;
}

matrix matrix::operator+(const matrix &o)
{
    matrix cpy(rows, columns);
    cpy.array = getArray();

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            cpy.array[i][j] += o.array[i][j];
        }
    }
    return cpy;
}

matrix matrix::operator-(const matrix &o)
{

}

matrix matrix::operator*(const matrix &o)
{

}

//set matrix as a 3 x 3
void matrix::setMatrix()
{
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            std::cout << "[ " << i+1 << "," << j+1 << " ]: ";
            std::cin >> array[i][j];
        }
    }
    system("cls");
}

//set matrix as a n x n
void matrix::setMatrix(int side)
{
    rows = columns = side;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            std::cout << "[ " << i+1 << "," << j+1 << " ]: ";
            std::cin >> array[i][j];
        }
    }
    system("cls");
}

//set matrix as a n x m
void matrix::setMatrix(int width, int height)
{
    rows = width, columns = height;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            std::cout << "[ " << i+1 << "," << j+1 << " ]: ";
            std::cin >> array[i][j];
        }
    }
    system("cls");
}

//this will print the matrix without problems.
void matrix::print()
{
    std::cout << std::endl;
    for (int i = 0; i < rows; i++) {
        std::cout << "|";
        for (int j = 0; j < columns; j++) {
            std::cout << "\t" << array[i][j] ;
        }
        std::cout << "\t|";
        std::cout << std::endl;
    }
    std::cout << std::endl;
}

//default destructor for deallocating memory.
matrix::~matrix()
{
    for (int i = 0; i < columns; i++) {
        delete [] array[i];
    }
    delete [] array;

}

El problema esta en estos dos métodos.

//returns a copy of the array pointer.
int matrix::getMatrix()
{
    int **copy = new int*[rows];

    for (int i = 0; i < rows; i++) {
        copy[i] = new int[columns];
    }

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            copy[i][j] = 0;
        }
    }

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            copy[i][j] = array[i][j];
        }
    }
    return **copy;
}

matrix matrix::operator+(const matrix &o)
{
    matrix cpy(rows, columns);
    cpy.array = getMatrix();

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            cpy.array[i][j] += o.array[i][j];
        }
    }
    return cpy;
}

y finalmente el main

#include "matrix.h"

int main()
{
    matrix A(2);
    matrix B(2);
    matrix C(2);
    A.setMatrix();
    B.setMatrix();
    C = A + B;
    C.print();
    return 0;
}

En ejecución Inserto 2 veces esto m1

Luego me imprime... resp

1 respuesta 1

2

Sobre tu pregunta

EDITADO:

La función getMatrix esta retornando un int cuando lo que necesitas es retornar un int **

Por otro lado, al sobrecargar el operator+, el objeto matrix cpy que creas local es descargado al sacarlo de la pila cuando haces return cpy;, lo cual invoca al operador delete y tu memoria es liberada por el destructor, de ahí la causa que te salgan números raros cuando vayas a imprimir el resultado.

Para corregirlo, he modificado el operator+ para devolver una referencia a un objeto creado dinámicamente.

Te pego el código completo en base al tuyo. Puedes también probarlo en este enlace, ten en cuenta que yo he tenido que sustituir los cin para poder ejecutar el programa sin tener que teclear nada:

#include <iostream>

class matrix
{
    int **array, rows, columns;
public:
    //constructors that allocates memory and fills the array with 0's
    matrix();
    matrix(int side);
    matrix(int width, int height);        

    int getRows() { return rows; }
    int getColumns() { return columns; }
    int **getMatrix(); //returns the array atrib

    matrix& operator+(const matrix &o);
    //set matrix methods write input data to the array
    void setMatrix();
    void print();

    ~matrix();
};

//default constructor without parameters.
matrix::matrix()
{
    //for allocating memory since our array is a pointer.
    rows = columns = 3;
    array = new int*[rows];

    for (int i = 0; i < rows; i++) {
        array[i] = new int[columns];
    }

    //just for making sure we don't have garbaje.
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            array[i][j] = 0;
        }
    }
}

//default constructor for square matrices.
matrix::matrix(int side)
{
    //for allocating memory since our array is a pointer.
    rows = columns = side;
    array = new int*[rows];

    for (int i = 0; i < rows; i++) {
        array[i] = new int[columns];
    }

    //just for making sure we don't have garbaje.
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            array[i][j] = 0;
        }
    }
}

matrix::matrix(int width, int height)
{
    //for allocating memory since our array is a pointer.
    rows = width, columns = height;
    array = new int*[rows];

    for (int i = 0; i < rows; i++) {
        array[i] = new int[columns];
    }

    //just for making sure we don't have garbaje.
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            array[i][j] = 0;
        }
    }
}

//returns a copy of the array pointer.
int **matrix::getMatrix()
{
    int **copy = new int*[rows];

    for (int i = 0; i < rows; i++) {
        copy[i] = new int[columns];
    }

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            copy[i][j] = 0;
        }
    }

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            copy[i][j] = array[i][j];
        }
    }
    return copy;
}

matrix& matrix::operator+(const matrix &o)
{
    matrix *cpy = new matrix(rows, columns);
    cpy->array = getMatrix();

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            cpy->array[i][j] += o.array[i][j];
        }
    }

    return *cpy;
}

void matrix::setMatrix()
{
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            array[i][j] = (i+1)*(j+1);
        }
    }
}

//this will print the matrix without problems.
void matrix::print()
{
    std::cout << std::endl;
    for (int i = 0; i < rows; i++) {
        std::cout << "|";
        for (int j = 0; j < columns; j++) {
            std::cout << "\t" << array[i][j] ;
        }
        std::cout << "\t|";
        std::cout << std::endl;
    }
    std::cout << std::endl;
}


//default destructor for deallocating memory.
matrix::~matrix()
{
    for (int i = 0; i < columns; i++) {
        delete [] array[i];
    }
    delete [] array;
}

int main()
{
    matrix A(2);
    matrix B(2);
    matrix C(2);
    A.setMatrix();
    B.setMatrix();
    C = A + B;
    C.print();

    return 0;
}

EDITADO2: Asumir que el tamaño de un puntero es el mismo que un int es muy cuestionable, el tamaño de un int es dependiente a la plataforma y el tamaño de un puntero de la arquitectura (32bits, 64bits, etc.). Vale que te coincida en la mayoría de ocasiones... pero eso no significa que estés comparando las mismas cosas.

3
  • que no es lo mismo especificar int **matrix::getMatrix() en función que retornar return **copy; lo digo porque un puntero es una dirección de memoria que puede almacenarse fácilmente en el espacio de memoria de un ìnt que son 4 bytes, por eso pienso, que no es lo mismo? probe esa pequeña diferencia y sigue imprimiéndome basura y no se porque, sera problema del compilador? el 20 jul. 2017 a las 22:32
  • @RenatoA. espero que te ayude la nueva edición, un saludo
    – David Isla
    el 21 jul. 2017 a las 9:12
  • muchas gracias, no tenia idea de eso de la sobrecarga el 22 jul. 2017 a las 23:59

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.