0

Hi all,

I'm mostly into my Java so I'm not even sure if I gave the post a proper heading. Basically I'm trying to read two matrices from the command line and print them out. Reading works as far as I can tell but when my program tries to call the printArr functions I get a segmentation fault. I think this is being caused because my pointers A and B are no longer pointing to the dynamic arrays once my function exits but the whole pointers thing is very new to me. Can anybody spot what the problem is?

```
#include <fstream>
#include <iostream>
using std::cout;
using std::endl;
using std::ofstream;
#include <math.h>
#include <stdlib.h>
typedef float** fArray;// in C++ multidimensional arrays are arrays of array pointers
void readArr(int, int, fArray);
void printArr(int, int, fArray);
int rows1;
int rows2;
int cols1;
int cols2;
int rowsum;
int colsum;
fArray A;
fArray B;
fArray Sum;
int main(int argc, char *argv[])
{
if(argc != 5)// incorrect number of parameters
{
cout<< "Usage : [" << argv[0]<<" rows1 cols1 rows2 cols2] where rows and cols are the number of columns and rows in a given matrix."<<endl;
}
else
{
//atoi converts a string to an integer
rows1 = atoi(argv[1]);//number of rows matrix 1
cols1 = atoi(argv[2]);//number of cols matrix 1
rows2 = atoi(argv[3]);//number of rows matrix 2
cols2 = atoi(argv[4]);//number of cols matrix 2
if(cols1 == rows2)//we can multiply these matrices
{
//matrixMult(rows1, cols1, rows2, cols2);//call multiplication function with command line arguments
readArr(rows1, cols1, A);
readArr(rows2, cols2, B);
printArr(rows1, cols1, A);
printArr(rows2, cols2, B);
}
else //must be unable to multiply matrices
{
cout<< "Unable to multiply matrices. The number of columns in matrix 1 must equal the number of rows in matrix 2. You supplied a value of" <<cols1<<" for the number of columns in matrix 1 and " <<rows2<<" for the number of rows in matrix 2."<<endl;
}
}
}
void readArr(int rows, int cols, fArray array)
{
array = new float*[rows]; //as noted above multidimensional arrays are arrays of arrays, new array[][] does not work so we need to create a 1d
for(int k = 0; k < rows; k++) // array and then iterate through the array with a for loop assigning each array as a further pointer which then
{ //completes the "2d" array.
array[k] = new float[cols];
}
for(int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
std::cin >> array[i][j];
}
}
}
void printArr(int rows, int cols, fArray array)
{
for(int i = 0; i < rows; i++)
{
cout<<endl;
for(int j = 0; j < cols; j++)
{
cout<< array[i][j] <<" ";
}
}
}
```