gpt4 book ai didi

c++ - 当通过交换行和列在双数组中设置值时,得到两个单元格值。为什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:11:50 28 4
gpt4 key购买 nike

使用以下代码:

#include <iostream>
#define M 3
#define N 5
using namespace std;
int n;
int m;
int my_array[N][M];
void print_a(){
cout << "array---------------------------------" << endl;
for (int i = 0; i < m; i++){
for (int j = 0; j < n; j++){
cout << my_array[i][j] << " ";
}
cout << endl;
}
}
int main() {
n = N;
m = M;
int j = n - 1;
for (int i = 0; i < m; i++){
my_array[i][j] = i + j;
print_a();
}
return 0;
}

array---------------------------------
0 0 0 0 4
0 4 0 0 0
0 0 0 0 0
array---------------------------------
0 0 0 0 4
0 4 0 0 5
0 5 0 0 0
array---------------------------------
0 0 0 0 4
0 4 0 0 5
0 5 0 0 6

double 数组中的两个单元格已更改。我知道双数组也是单数组。所以,即使是 col 和 row 也被交换了。不应该有两个单元格被改变。这是为什么?

最佳答案

在打印函数中将 n 换成 m。

#include <iostream>
#define M 3
#define N 5
using namespace std;
int n;
int m;
int my_array[N][M];
void print_a(){
cout << "array---------------------------------" << endl;
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++){
cout << my_array[i][j] << " ";
}
cout << endl;
}
}
int main() {
n = N;
m = M;
int j = n - 1;
for (int i = 0; i < m; i++){
my_array[i][j] = i + j;
print_a();
}
return 0;
}

it works.

array---------------------------------
0 0 0
0 4 0
0 0 0
0 0 0
0 0 0
array---------------------------------
0 0 0
0 4 0
0 5 0
0 0 0
0 0 0
array---------------------------------
0 0 0
0 4 0
0 5 0
0 6 0
0 0 0

代码中的问题:最后一列中的数字实际上是下一行的值(第二列)。这是由于您机器上二维数组的 cpp 布局。 link

关于c++ - 当通过交换行和列在双数组中设置值时,得到两个单元格值。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40122931/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com