簡體   English   中英

C ++-在函數之間傳遞數組

[英]C++ - Passing array from function to function

所以我有這段代碼:

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;
}

矩陣文件

#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;
}

矩陣

#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:


};

它可以正常運行,但問題是,顯示矩陣時獲得不同的值? 我想我正在獲取數組的地址,如何從中獲取價值? 我認為傳遞數組是正確的。

 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輸入int,才將a[0][0]分配給新值。 看見? 您永遠不會去a [0] [1]等。只有第一個元素將是有效的,其余元素將保持未初始化,因為在第一次執行while循環之后,istringstream對象中沒有剩余任何字符。

因此要更正它:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM