我有一个结构,根据用户在运行时的输入,它将需要一维数组或3D数组。它永远不会需要两者。现在,我已经像下面的示例代码中那样设置了它,其中单独的变量可以指向一维数组或3D数组。我想在结构中只有一个变量可以指向一维数组或维数在运行时设置的3D数组。我有C的中级知识,并且是C++的初学者。我愿意接受一个基于C++概念的答案,但如果没有减速(或可以忽略的减速),则与相比只有。如果它是一个3D数组,那么访问和更改数组值的for循环是我的代码中最大的瓶颈。一旦数组被设置,我就不需要改变数组的尺寸或大小。在运行时设置数组维数
有没有办法做到这一点,或者我应该解决在我的结构中总是有一个无关的变量?
#include <iostream>
using namespace std;
typedef struct {
int dim;
int *one_d_arr;
int ***three_d_arr;
} Struct;
int main() {
int count = 0;
int *arr1 = (int*) malloc(2 * sizeof(int));
arr1[0] = 0;
arr1[1] = 1;
int ***arr3 = (int***) malloc(2 * sizeof(int**));
for (int i=0; i<2; i++) {
arr3[i] = (int**) malloc(2 * sizeof(int*));
for (int j=0; j<2; j++) {
arr3[i][j] = (int*) malloc(2 * sizeof(int));
for (int k=0; k<2; k++) {
arr3[i][j][k] = count++;
}
}
}
Struct s;
s.one_d_arr = NULL;
s.three_d_arr = NULL;
cout << "Enter number of dimensions: ";
cin >> s.dim;
if (s.dim==1) {
s.one_d_arr = arr1;
cout << s.one_d_arr[0] << ", " << s.one_d_arr[1] << endl;
}
else if (s.dim==3) {
s.three_d_arr = arr3;
cout << s.three_d_arr[0][0][0] << ", " << s.three_d_arr[0][0][1] << endl;
cout << s.three_d_arr[0][1][0] << ", " << s.three_d_arr[0][1][1] << endl;
cout << s.three_d_arr[1][0][0] << ", " << s.three_d_arr[1][0][1] << endl;
cout << s.three_d_arr[1][1][0] << ", " << s.three_d_arr[1][1][1] << endl;
}
else {
cout << "Must enter 1 or 3" << endl;
}
}
'C/C++'是UB .. –
我想你可能想用用C'new'(而不是'malloc')++。 – pzaenger
所以标签以'C++'结尾 - 对我来说看起来更像'c'风格。 – 4386427