打印包含 2D 数组的结构

Printing an struct that includes an 2d array

本文关键字:结构 数组 2D 包含 打印      更新时间:2023-10-16

已编辑我正在尝试做的是(从文件中读取并将信息放入结构中定义的 2d 数组中后,该部分有效)调用一个方法,该方法找出数组中是否有任何零,如果是,请更改它并再次打印。我知道我错过了指针,但我不知道在哪里。提前谢谢。

struct matrix{
const static int N=9;
int Ar[N][N];
};
void iprint(matrix s){ //my method to print the array
    for(int i = 0; i < 9; i++) {
        for(int j = 0; j < 9; j++) {
            cout << (s).Ar[i][j] << ' ';
        }
        cout << endl;
    }
}
bool annotation(matrix s, int row, int column, int num){
    if(s.Ar[row][column] == 0){
        (s).Ar[row][column] = num;
        return true;
    }
    else if(s.Ar[row][column] != 0){
        cout << "NO" << endl;
        return false;
    } else {
        cout << "No" << endl;
        return false;
    }
    iprint(s);
}

排在第一位的数组:

0 0 6 5 0 0 1 0 0
4 0 0 0 0 2 0 0 9
0 0 0 0 3 0 0 0 8
0 7 0 1 0 0 5 0 0
0 8 0 0 0 0 0 6 0
0 0 3 0 9 0 0 4 0
2 0 0 0 4 0 0 0 0
9 0 0 7 0 0 0 0 3
0 0 5 0 0 8 2 0 0

我在这些方法之后得到的输出(调用方法annotation(s,1,1,2);

2686428 0 0 2686524 8989288 4733208 0 0 -17974607
1 0 4201360 4662484 0 8989288 8989340 9005760 0
.
.
.

我从文件中读取数组,方法是

bool readMatrix(matrix s){
ifstream f;
f.open("nuMatrix.txt");
if (f.is_open()) {
    while(!f.eof()){
    for(int i=0;i<9;i++){
        for(int j=0;j<9;j++){
            f>>(s).Ar[i][j];
            }
        }
    }
    f.close();
    iprint(s);
    return true;
}
else {
    cerr << "NO";
    return false;
}

}'

你传递给readMatrixannotation的矩阵不会被函数修改。
您是按值传递矩阵的,因此您只是修改它的副本。

更改函数以引用matrix

bool annotation(matrix& s, int row, int column, int num)
bool readMatrix(matrix& s)