首页 > 解决方案 > 从 C++ 中的 int 方法返回一个数组

问题描述

我正在为具有两个函数的多维数组编写代码。
第一个函数(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);   
}  

标签: c++

解决方案


试试这种方式:

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

推荐阅读