Jonathan Mee
Jonathan Mee

Reputation: 38919

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?

Upvotes: 1

Views: 134

Answers (4)

HolyBlackCat
HolyBlackCat

Reputation: 96053

Since it's C++ rather than C, I would write a proper type trait:

#include <cstddef>
#include <type_traits>

template <typename T>
inline constexpr std::size_t total_extent_v = 1;

template <typename T, std::size_t N>
inline constexpr std::size_t total_extent_v<T[N]> = N * total_extent_v<T>;

Usage:

std::cout << total_extent_v<Matrix3x3> << '\n';

If this is too much and you want something simpler, I would use a std::remove_all_extents_t-based solution as suggested by @StoryTeller.

Upvotes: 2

R Sahu
R Sahu

Reputation: 206567

You can use:

sizeof(Matrix3x3)/sizeof(float)

Upvotes: 1

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.

Upvotes: 4

SergeyA
SergeyA

Reputation: 62563

First of all, you want to divide, not multiply. Second of all, customary way would be

auto n_elements = sizeof(Matrix3x3) / sizeof(std::declval<Matrix3x3>()[0][0]);

That gives expected value of 9.

Upvotes: 2

Related Questions