I need to store n * 2 values in some array.
I can easily do that like this
int n=5; //in real world this is calculated at runtime
int* arr;
arr = new int[n*2]
//fill arr with values
It's not a coincidence that I need arr to have n X 2 value and not simply n, arr stores pairs of values.
I could simply know what's stored and how, and access these pairs by offsetting the index by n,
cout<<"first pair is"<<arr[0]<<","<<arr[n];
cout<<"second pair is"<<arr[1]<<","<<arr[n+1]
cout<<"last pair is"<<arr[n-1]<<","<<arr[n+n-1]
But it would be so cool, if I could access these values as if they are in a 2 dimensional array, e.g.
cout<<"first pair is"<<arr[0][0]<<","<<arr[0][1];
cout<<"second pair is"<<arr[1][0]<<","<<arr[1][1];
cout<<"last pair is"<<arr[n][0]<<","<<arr[n][1]
The reason I'm not just declaring arr as a bidimensional array is that n is only known at runtime.
Can this be done in some way in C++?
Edit: I strongly prefer arrays over any other object structures for performance reasons. I know the performance differences is practically non-existent on modern computers, but this is my constraint. It has to still be just some integers stored in a contiguous piece of memory.
Edit about duplicate: The question that has been suggested as duplicate hits very close to home, although not exactly, but the answer to that question is just a workaround and not a direct answer. I would be happier to simply have an authoritative answer that it is not possible, rather than having alternative solutions. I am not looking for solutions, since I already have a solution in the question itself. I am looking for an answer to my question.
As long as 2 is a compile time constant, you can easily do this in C++:
const int n = 7;
int (*arr)[2] = new int[n][2];
arr[2][1] = 42;
This declares arr as a pointer *arr to an array of two elements (*arr)[2] which are integers int (*arr)[2]. This new pointer is initialized with a suitable pointer allocated with new.
The parentheses around (*arr) are necessary because the array subscript operator [] has higher precedence than the indirection operator *, and the parentheses force the correct order of operators.
Usage of the resulting pointer is exactly as you want, the memory is allocated in one piece, and you get rid of it with a simple
delete[] arr;
The compile-time-constant restriction is only present in C++, C is more lenient, allowing you to write stuff like
void foo(int width, int height) {
int (*image)[width] = malloc(height*sizeof(*image));
image[height-1][width-1] = 42;
...
where both dimensions of the 2D array are dynamic. C++ forbids this, forcing you to use compile-time sizes for all but the outermost dimension.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With