3

How would I find the size in bytes of an array like this?

    double dArray[2][5][3][4];

I've tried this method but it returns "2". Maybe because the array is only declared and not filled with anything?

     #include <iostream>
     #define ARRAY_SIZE(array) (sizeof((array))/sizeof((array[0])))
     using namespace std;

      int main() {
        double dArray[2][5][3][4];
        cout << ARRAY_SIZE(dArray) << endl;
       }
2
  • do you want the size in terms of bytes or the size in terms of how many elements are in the entire array? Commented Apr 23, 2013 at 17:26
  • To get the total number of elements in an array (here: 2*5*3*4), you can use something like template<class T> constexpr std::size_t get_element_count(T const& a) { return sizeof(T)/sizeof(typename std::remove_all_extents<T>::type); } Commented Apr 23, 2013 at 17:41

2 Answers 2

5

How would I find the size in bytes

This tells you how many elements are present in an array. And it gives the expected answer of 2 for dArray.

#define ARRAY_SIZE(array) (sizeof((array))/sizeof((array[0])))

If what you want it the byte count, this will do it.

#define ARRAY_SIZE(array) (sizeof(array))

Maybe because the array is only declared and not filled with anything?

That won't affect the behavior of sizeof. An array has no concept of filled or not filled.

Sign up to request clarification or add additional context in comments.

5 Comments

Is there a reason for the double brackets in the first macro ((array))?
@DyP No functional reason that I'm aware of. It's the code presented in the question. :)
Pretty sure OP is having more trouble getting 2*5*3*4 than converting from elem to bytes.
One could argue the name of the first macro would be clearer if it was ARRAY_LENGTH (or ARRAY_EXTENT). Also, there's the C++11 approach using std::extent, like template<class T> constexpr std::size_t get_extent(T const& a) { return std::extent<T>::value; }
OIC. Nevermind, this is right - problem is array[0] was giant so OP should have been dividing by sizeof array[0][0][0][0] to get elem count.
2

array[0] contains 5 * 3 * 4 elements so sizeof(array) / sizeof(array[0]) will give you 2 when the first dimension of your array is 2

Rewrite your macro as:

#define ARRAY_SIZE(array, type) (sizeof((array))/sizeof((type)))

to get the number of elements,

or simply sizeof(array) to get the number of bytes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.