gpt4 book ai didi

C++ - 将数组从一个函数传递到另一个函数

转载 作者:行者123 更新时间:2023-11-28 05:32:07 26 4
gpt4 key购买 nike

所以我有这段代码:

主要.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;
}

矩阵.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;
}

矩阵.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:


};

它运行没有错误,但问题是,我在显示矩阵时得到了不同的值?我想我正在获取数组的地址。如何从中获取值?我认为传递我的数组是正确的。

最佳答案

 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 和 j = 0

然后你进入了while循环。

在这里,直到您从 stringstream 输入整数,您才将 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;
}
}

关于C++ - 将数组从一个函数传递到另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39248184/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com