I have a struct, which, depending on user inputs at runtime, will either require a 1D array or a 3D array. It will never need both. Right now, I have it set up like in the sample code below, with separate variables that can point to either a 1D array, or a 3D array. I would like to have just one variable in the struct that can point to either a 1D array or a 3D array, where the dimension is set at runtime. I have intermediate knowledge of C, and am a beginner with C++. I'd be willing to accept an answer based on C++ concepts but only if there is no slowdown (or negligible slowdown) compared to using C when iterating over the values. If it's a 3D array, then the for loops that access and change the array's values are the biggest bottleneck in my code. Once the array is set up, I won't need to change the dimension or size of the array.
Is there a way to do this, or should I just settle for always having an extraneous variable in my struct?
#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; } }
new(instead ofmalloc) in C++.set array size at runtime == std::vector