Here is my code, the aim is to use dynamic memory and pointers. The program siccesfuly reads in data from a text file into the dynamic array(matrix). The size of the array is also in the text file, so thats how the size of the array is known. I am required to pass the pointer to the matrix(1 dimensional array just for now) to the caller so it can be used in a print function. Using "return matrix;" does not seem to work. Any ideas? Also i am not allowed to change any of the function headers, and can assume the data file will also contain data of type float.
main.cpp
#include <iostream>
#include <fstream>
#include "matrix-1.h"
using namespace std;
int main ()
{
char filename[10];
cout << "Enter filename to open: " << endl;
cin >> filename;
int rows;
int columns;
readmatrix(filename, rows, columns);
printmatrix(matrix, columns, rows);//main dosnt recognise matrix
return 0;
}
matrix-1.cpp
#include <iostream>
#include <fstream>
#include "matrix-1.h"
using namespace std;
float* readmatrix(char filename[], int& rows, int& columns)
{
ifstream ins;
ins.open(filename, ios::in | ios::out);
if(ins.good())
{
ins >> rows >> columns;
float* matrix = new float[rows * columns];
for (int i = 0; i < (rows * columns); i++)
{
ins >> matrix[i];
}
return matrix; //if i put this at the end it isnt in scope
}
else
{
cout << "the shit didnt work" << endl;
return NULL;
}
cout << rows << endl;
cout << columns << endl;
ins.close();
return 0;
}
matrix.cpp
#include <iostream>
#include <fstream>
#include "matrix-1.h"
using namespace std;
//the matrix pointer isnt getting passed to this function.
void printmatrix(float matrix[], int columns, int rows)
{
for (int i = 0; i < (rows * columns); i++)
{
cout << matrix[i]<< endl;
}
return 0;
}
matrix-1.h
float* readmatrix(char[], int&, int&);
void printmatrix(float[], int, int);