从 C++ 中的 int 方法返回一个数组



我正在为具有两个函数的多维数组编写代码。
第一个函数(read()(获取每个数组的值,第二个函数显示每个数组的值。

我的问题是从读取函数返回 geted 数组。

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

以下是你的错误:

  1. 您不需要从函数返回任何内容read因为传递给此函数的参数是作为指针传递的。因此,这些地址上的内容将根据用户输入进行更新。这是非常好的功能签名void read(Sec sec);

  2. main函数中,首先需要初始化局部变量Sec 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)
}

最新更新