【发布时间】:2019-11-07 05:38:40
【问题描述】:
所以我的部分作业是编写一个读取二维数组参数的程序。
这是我的代码:
#include <iostream>
#define ROWCAP 100
#define COLCAP 100
using namespace std;
void readValues(int x, int y, double matrix[x][y]);
void printValues(int x, int y, double matrix[x][y]);
int main() {
int row;
int cols;
cout<<"Enter the number of rows: ";
cin>>row;
while(row>ROWCAP){
cout<<"Number is too large, try again: ";
cin>>row;
}
cout<<"Enter the number of columns: ";
cin>>cols;
while(cols>COLCAP){
cout<<"Number is too large, try again: ";
cin>>cols;
}
double matrix[row][cols];
cout<<"Enter the matrix: \n";
readValues(row,cols,matrix[row][cols]);
cout<<"\nThe matrix entered was:\n";
printValues(row,cols,matrix[row][cols])
return 0;
}
void readValues(int x, int y, double matrix[x][y])
{
for(int i=0; i<x; i++)
{
for(int j=0; j<y; j++)
{
cin>>matrix[i][j];
}
}
}
void printValues(int x, int y, double matrix[x][y])
{
for(int i=0; i<x; i++)
{
for(int j=0; j<y; j++)
{
cout<<matrix[i][j]<<"\t";
}
cout<<endl;
}
}
这些是错误:
error: 'matrix' declared as array of references of type 'double &'
void readValues(int x, int y, double &matrix[x][y]);
我已经坚持了三个小时。我做错了什么?
附言只能使用iostream
【问题讨论】:
-
define->#define和void readValues(int x, int y, double &matrix[x][y]);->void readValues(int x, int y, double matrix[x][y]);(你在main()中声明数组,只是传递它,而不是指向它的指针) -
double matrix[row][cols];-- C++ 中没有 VLA(可变长度数组)(非标准编译器扩展除外)。为什么不使用向量的向量?如果你必须使用普通的double,那么你需要动态分配或声明double matrix[ROWCAP][COLCAP];,并且只对row, col定义的空间进行操作(这有其缺点,但可行) -
不要编辑你的问题来合并你在 cmets 中得到的答案,然后切换到另一个问题,这被认为是一个移动目标问题(如果你已经得到官方答案,真的不感激..)。如果您至少也调整了所有问题,那么它仍然适合新问题。 IE。发布您现在收到的正确错误消息,而不是旧的错误消息。请再次edit您的问题以解决该问题,而不是在对部分旧问题的评论中解释新问题。
-
那么您是否了解了可变长度数组及其特殊的非便携方面?您是否已经了解了所用编译器的假设,这意味着什么?如果不是,但您已经了解了所有编译器都知道要创建但需要静态大小定义的普通数组,那么请使用它们。这是相当困难的。
标签: c++ matrix parameters