2

I'm trying to create a function which I can use to dynamically allocate and input values of a matrix, and another matrix to output the results. I get an error, saying my matrix is not an array, pointer or vector.

#include <iostream>
using namespace std;

double data_entry_matrix(int ARows, int ACols);

void output_matrix(double **A, int ARows, int ACols);


int main()
{
    int ARows=3;
    int ACols=3;
    
    cout << "Input matrix: " << endl;
    double A = data_entry_matrix(ARows,ACols);
    cout << "The matrix is: " << endl;
    
    output_matrix(A, ARows, ACols);
    
}

double data_entry_matrix(int ARows, int ACols)
{

    double** A;
    A = new double* [ARows];
    for (int i=0;i<ARows;i++){
        A[i] = new double [ACols];
    }
    
    for(int i=0;i<ARows;i++)
    {
        for(int j=0;j<ACols;j++)
       {
           cin>>A[i][j];
       }
    }
    return **A;
}

void output_matrix(double **A,int ARows, int ACols)
{
    cout << "The matrix is: " << endl;
    for(int i=0;i<ARows;i++){
        for(int j=0;j<ACols;j++){
           cout << A[i][j] << "\t";
            
        }
        cout << "\n";
    }
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
DHJ
  • 611
  • 2
  • 13

1 Answers1

3

You have to return and hold the pointer double**, not single double.

#include <iostream>
using namespace std;

double** data_entry_matrix(int ARows, int ACols); // change return type to return a pointer

void output_matrix(double **A, int ARows, int ACols);


int main()
{
    int ARows=3;
    int ACols=3;
    
    cout << "Input matrix: " << endl;
    double** A = data_entry_matrix(ARows,ACols); // change type to hold a pointer
    cout << "The matrix is: " << endl;
    
    output_matrix(A, ARows, ACols);
    
}

double** data_entry_matrix(int ARows, int ACols) // change return type to return a pointer
{

    double** A;
    A = new double* [ARows];
    for (int i=0;i<ARows;i++){
        A[i] = new double [ACols];
    }
    
    for(int i=0;i<ARows;i++)
    {
        for(int j=0;j<ACols;j++)
       {
           cin>>A[i][j];
       }
    }
    return A; // stop dereferencing to return the pointer
}

void output_matrix(double **A,int ARows, int ACols)
{
    cout << "The matrix is: " << endl;
    for(int i=0;i<ARows;i++){
        for(int j=0;j<ACols;j++){
           cout << A[i][j] << "\t";
            
        }
        cout << "\n";
    }
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70