【发布时间】:2020-10-28 14:26:01
【问题描述】:
我认为我的代码是正确的,但我仍然无法转置我的数组
我应该为malloc transpose 的变量正确编码吗?
int *arr = (int *)malloc(r * c * sizeof(int));
int *transpose = (int *)malloc(c * r * sizeof(int));
这是我的输入:
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
cout << "Element at x[" << i << "][" << j << "] : ";
cin >> *(arr + i * c + j);
}
}
转置码对吗?
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
*(transpose + j + i * c) = *(arr + i * c + j);
}
cout << endl;
}
打印代码对吗?
cout << endl << "transpose : " << endl;
for (i = 0; i < c; i++) {
for (j = 0; j < r; j++) {
cout << *(transpose + i * c + j ) << " ";
}
cout << endl;
}
【问题讨论】:
-
你应该避免在 C++ 中使用 malloc。
-
为什么不使用
[]运算符,如arr[i*c + j]而不是*(arr + i*c + j)? -
我建议将这些原始指针包装在一个知道矩阵形状并为您进行正确计算的小类中。