Maximum number of indexes for N-dimensional array?

Hello,

I am trying to find the maximum value I can put for each dimension in a 2D array, but trying obvious things like USHRT_MAX (since that's the max for a 1D), or SHRT_MAX (since that would be equal to dividing a USHRT_MAX by the number of dimensions in the array), but both cases crash the program on start up (I am admittedly making the assumption here, that since a 1D array of greater than the USHRT_MAX limit crashes a 1D array, the crash is due to breaking the max number of indexes limit for a 1D array).

I worded the question as N-dimensional in case I would need to know the max number of indexes for a higher number of dimensions in the future, again assuming there is a general formula for this.

Thanks!
Theoretically the limit depends on your operating system, if you have a 16-/32-/64-bit os, you can't have more than 2^n -1 elements.
The standard has a value type that can hold exactly that many values: std::size_t
so the maximum is: std::size_t max_values(-1);

The theoretical maximum is 2^n-1, the true limit is the size of your unused RAM when executing the application.
Note, that bigger datatypes require more space and therefore the limit is to be divided by the size of the datatype.
Last edited on
I am trying to find the maximum value I can put for each dimension in a 2D array, ...

Gamer2015 has already pointed out the limit is actually on the number of elements in your array, rather than the individual dimensions. Afterall, (normal) computer memory is linear.

For an array with multiple dimensions you need to keep the dimensions small enough that their product multiplied by the size of each element is less than or equal to the available memory. e.g. array int data[N][M]; it's going to take N x M x sizeof(int) bytes (int can be 16, 32, 64 bit, that is 2, 4, or 8 byte. Or even more.)

(Unless you arbitrarily decide that the maximum size of a square array (cube array, etc) sets the maximum for an array?)

Indidentally, the size Gamer2015 is talking about is assuming you're allocating the array with new, where you can access a lot of memory. If you are working with a stack variable the amount of space is a lot smaller. With Microsoft Visual Studio's C++ compiler, the default stack size is 1 MB per thread. And this has to hold all the variables in the functions on the current call stack.

If a stack variable could use the whole of the stack memory then, for a square array of 32-bit ints, the maximum value of the dimensions would be 512. A good bit smaller even than USHRT_MAX = 65535.

Andy
Last edited on
Topic archived. No new replies allowed.