Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding size of multidimensional array

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;
       }
like image 880
kxf951 Avatar asked Apr 27 '26 02:04

kxf951


2 Answers

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.

like image 135
Drew Dormann Avatar answered Apr 28 '26 16:04

Drew Dormann


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.

like image 23
Dave Rager Avatar answered Apr 28 '26 16:04

Dave Rager