C++ 从c+;中的int方法返回数组+;
我正在为具有两个函数的多维数组编写代码。C++ 从c+;中的int方法返回数组+;,c++,C++,我正在为具有两个函数的多维数组编写代码。 第一个函数(read())获取每个数组的值,第二个函数显示每个数组的值 我的问题是从read函数返回获取的数组 #include <iostream> #include <ctime> #include <cstdlib> #include <cmath> #include <time.h> #include<cassert> /* run this program using th
第一个函数(
read()
)获取每个数组的值,第二个函数显示每个数组的值
我的问题是从read函数返回获取的数组
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <cmath>
#include <time.h>
#include<cassert>
/* run this program using the console pauser or add your own getch,
system("pause") or input loop */
using namespace std;
typedef int Sec[2][2];
int read(Sec sec){
for (int i=0;i<2;i++){
for (int j=0;j<2;j++){
cin>>sec[i][j];
}
}
return sec;
}
void sho(){
for (int i=0;i<2;i++){
for (int j=0;j<2;j++){
cout<<sec[i][j];
}
}
}
int main() {
read(Sec sec);
sho(sec);
}
#包括
#包括
#包括
#包括
#包括
#包括
/*使用控制台暂停器运行此程序或添加您自己的getch,
系统(“暂停”)或输入循环*/
使用名称空间std;
typedef int Sec[2][2];
整数读取(秒){
对于(int i=0;isec[i][j];
}
}
返回秒;
}
void sho(){
对于(int i=0;i,以下是您的错误:
您不需要从read
函数返回任何内容,因为传递到此函数的参数是作为指针传递的。因此,这些地址上的内容将根据用户输入进行更新。这是非常好的函数签名void read(Sec);
在main
函数中,首先需要初始化局部变量Sec;
,然后将其传递给read
函数,如下所示read(Sec);
希望这对您有所帮助!请尝试以下方法:
#include <iostream>
//you dont need ctime here
#include <ctime>
//you dont need csdtlib here
#include <cstdlib>
//you dont need cmath here
#include <cmath>
//you dont need time.h here
#include <time.h>
//you dont need cassert here
#include<cassert>
/* run this program using the console pauser or add your own getch,
system("pause") or input loop */
using namespace std;
typedef int Sec[2][2];
//by adding the "&" symbol you give the function read a refrenze to a variable of
//type sec, which allows to change the values, it is like a derefrenzed pointer
void read(Sec& sec){
for (int i=0;i<2;i++){
for (int j=0;j<2;j++){
cin>>sec[i][j];
}
}
}
//you dont need a refrenze here, because u just want to read from the Sec object, if
//you want to run a bit faster you couldnt use:
//void show(const Sec& sec),
//this would give the function show a refrenze you cant edit, so perfectly for
//reading values
void show(Sec sec){
for (int i=0;i<2;i++){
for (int j=0;j<2;j++){
cout<<sec[i][j];
}
}
}
int main() {
Sec sec;
read(sec);
show(sec)
}
#包括
//你不需要我在这里
#包括
//这里不需要csdtlib
#包括
//这里不需要cmath
#包括
//你不需要时间
#包括
//这里不需要卡塞特
#包括
/*使用控制台暂停器运行此程序或添加您自己的getch,
系统(“暂停”)或输入循环*/
使用名称空间std;
typedef int Sec[2][2];
//通过添加“&”符号,可以为函数read refrenze赋予变量
//键入sec,它允许更改值,就像一个解除频率的指针
无效读取(秒和秒){
对于(int i=0;isec[i][j];
}
}
}
//这里不需要refrenze,因为您只想从Sec对象读取,如果
//您想跑得快一点,但无法使用:
//无效显示(常数秒和秒),
//这将使函数显示一个您无法编辑的refrenze,这对于
//读取值
无效显示(秒){
对于(int i=0;i请注意,正确格式化代码非常重要。另外,read(Sec);
是错误的。您可能想要Sec;read(Sec);
。您的代码甚至没有编译,您至少可以提供一个函数示例吗?(请参阅。您做了什么?键入int for Sec[][]?为什么?不使用typedef int或任何其他保留关键字返回type:std::array?@M.shahbazi检查以下答案