Search code examples
c++arraysmultidimensional-arraytypedefsizeof

Size of a Typedef'd 2-Dimensional Array


Given a typedefined 2-dimensional array:

typedef float Matrix3x3[3][3];

If I want to get the total number of floats in Matrix3x3 I feel like I should be able to just do:

sizeof(Matrix3x3) / sizeof(**Matrix3x3)

But obviously I cannot dereference a type. What is the best way to do this?


Solution

  • You can use std::remove_all_extents.

    sizeof(Matrix3x3) / sizeof(std::remove_all_extents_t<Matrix3x3>)
    

    It's a trait that essentially removes all the square brackets from the array type, no matter how many dimensions.