How to extract the n-th dimension of a multidimensional array?

Let's say I have a multidimensional array, for instance:
 
unsigned short arr[8][51][23][42];

How can I extract the n-th dimension of that array? Something like arrDim(2) = 23? (It does not have to be a function)
Last edited on
Don't.

Define the array dimension sizes with constants and just refer to those.

You may have trouble getting an array of that size on the stack.


This may or may not give you the numbers you want, but I wouldn't rely on it.
1
2
3
4
5
6
7
8
9
10
#include <iostream>

int main()
{
   static unsigned short arr[8][51][23][42];
   std::cout << sizeof arr[0][0][0] / sizeof arr[0][0][0][0] << '\n';
   std::cout << sizeof arr[0][0] / sizeof arr[0][0][0] << '\n';
   std::cout << sizeof arr[0] / sizeof arr[0][0] << '\n';
   std::cout << sizeof arr  / sizeof arr[0] << '\n';
}
Last edited on
There is std::rank which returns the number of dimensions and std::extent to return the size of a dimension.

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <type_traits>

int main() {

	unsigned short arr[8][51][23][42];

	std::cout << "Rank is: " << std::rank_v<decltype(arr)> << '\n';
	std::cout << "Extent of dimension 2 is: " << std::extent_v<decltype(arr), 2> << '\n';
}



Rank is: 4
Extent of dimension 2 is: 23

Last edited on
Topic archived. No new replies allowed.