0

を機能させる関数から配列を渡す:C++ - だから私はこのコードを持って

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: 


}; 

これはエラーなく実行されますが、問題は、マトリックスを表示しているときに別の値になっていますか?私は配列のアドレスを取得していると思います。どうすれば値を取得できますか?私は自分の配列を渡すことが正しいと思う。

+1

は、時計ウィンドウ開いていると、デバッガツールの使用を検討してステップにより、コードのステップを経ます。この種の問題を扱うのは本当に良いです – alexeykuzmin0

+1

配列の代わりにstd :: vectorを使うことも考えてください。これらの悲しみ(あなたがそこに見ていないメモリリークを含む)はすべて消え去ります:) –

+1

問題を再現する[MCVE]を提供できますか。また、コードのデバッグ中に観察したことに関する情報を追加します。初期化されていない値を_addresses_ではなくarr [i] [j] 'から出力する可能性があります。 –

答えて

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

これは実際にはかなり間違っています。あなたがここで何をしているのか見てください。 先頭に戻るi = 0 and j = 0

あなたはwhileループに入っています。

ここで、stringstreamからintsを入力するまで、a[0][0]に新しい値を割り当てます。 それを見ますか? whileループ の最初の実行の後に、istringstreamオブジェクトに残っている文字がないため、[0] [1]などには決して移動しません。最初の要素だけが有効になり、残りは初期化されずに残ります。

ので、それを修正する:

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

これを指摘してくれてありがとう、私はこれが問題だと思う。 – Zelgh

+0

問題はありませんが、いくつかの問題が発生した場合に役立つコードを追加しましたが、あなた自身ですでに解決していることは間違いありません。 – MindRoller

+0

訂正してくれてありがとう、私はそれについて考えなかった! – Zelgh