Zelgh Zelgh - 3 months ago 17
C++ Question

C++ - Passing array from function to function

So I have this code:

main.cpp

#include "matrix.h"

int main(int argc, char *argv[])
{


matrix m;
regularMatrix rMatrix;

rMatrix.setDetails(3, "1 2 3 4 5 6 7 8 9");
//rMatrix.displayMatrix();

//int i, j, r = 0, c = 0, a;


//cout << "Enter number of Rows and Columns: " << endl;

//cin >> r ;












system("PAUSE");
return EXIT_SUCCESS;
}





matrix.cpp

#include "matrix.h"

int rows = 3, columns = 3;
int **a;




void matrix::displayMatrix(int **arr)
{

cout << "Values Of 2D Array [Matrix] Are : ";
for (int i = 0; i < rows; i++ )
{
cout << " \n ";
for (int j = 0; j < columns; j++ )
{
cout << arr[i][j] << " ";
}
}
}

void matrix::setDetails(int dimension, string y)
{
int f = dimension;
rows = dimension;
columns = rows;
string input = y;

istringstream is(input);
int n;

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



for ( int i = 0; i < rows; i++ )
{
for ( int j = 0; j < columns; j++ )
{
while ( is >> n)
{
a[i][j] = n;
//cout << a[i][j] << endl;
}
}
}



matrix::displayMatrix(a);

//cout << f << endl << g << endl;
}





matrix.h

#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

class matrix
{
public:
virtual void displayMatrix(int** arr);
virtual void setDetails(int dimension, string y);
//virtual void setMatrix(int m[]);
//virtual void printArray(int** i);


};

class regularMatrix : public virtual matrix
{
public:


};


It runs without error but the problem is, I'm getting different value when I'm displaying the matrix? I think I'm getting the address of the array.How will I get the value out of it? I think I'm right about passing my array.

Answer
 for  (  i  =  0;  i  <  rows;  i++  )
 {
      for  (  j  =  0;  j  <  columns;  j++  )
      {
           while ( is >> n)
           {
                 a[i][j] = n;
                 //cout << a[i][j] << endl;
           }
      }
 }

This is actually pretty wrong. Look what you're doing here. At beggining, you have i = 0 and j = 0

Then you got into the while loop.

And here until you input ints from stringstream you assign a[0][0] to new value. See it? You never go to a[0][1] etc. Only first element will be valid and the rest will stay uninitialized, because after first execution of your while loop there is no characters left in the istringstream object.

So to correct it:

for  (  i  =  0;  i  <  rows;  i++  )
     {
          for  (  j  =  0;  j  <  columns;  j++  )
          {
              if ( is >> n )
              a[i][j] = n;
          }
     }