I have a multidimensional array consisting of several sub arrays. Is it possible to count the number of sub-arrays in the array?
-
Like array[5][4][3][2] and you want to know the lower dimension sizes? – Michael Dorgan Apr 14 '15 at 21:26
2 Answers
If the array is declared on the stack, then you can get the number of elements by using the sizeof()
function:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[3][4];
fprintf(stdout, "size of a in bytes: %zu\n", sizeof(a));
fprintf(stdout, "size of a[0][0] in bytes: %zu\n", sizeof(a[0][0]));
fprintf(stdout, "number of elements in a: %zu\n", sizeof(a)/sizeof(a[0][0]));
int b[3][4][5];
fprintf(stdout, "size of b in bytes: %zu\n", sizeof(b));
fprintf(stdout, "size of b[0][0][0] in bytes: %zu\n", sizeof(b[0][0][0]));
fprintf(stdout, "number of elements in b: %zu\n", sizeof(b)/sizeof(b[0][0][0]));
return EXIT_SUCCESS;
}
To compile:
$ gcc -Wall stack_array_test.c -o stack_array_test
Results:
$ ./stack_array_test
size of a in bytes: 48
size of a[0][0] in bytes: 4
number of elements in a: 12
size of b in bytes: 240
size of b[0][0][0] in bytes: 4
number of elements in b: 60
Knowing this, you could modify the denominator to get sizes of elements at different dimension indices. I'll leave that as an exercise.
Now, if your array is declared dynamically — on the heap — then you cannot use this technique.
You could create a struct
to mimic a vector, which stores the pointers, along with a size_t
representing the number of elements. You could extend this idea to keep a vector of vectors, or a vector of vectors of vectors, and so on. Getting the number of "subarrays" would be a matter of looking up the size parameter of each nested vector and keeping a running tally.

- 1
- 1

- 95,983
- 54
- 240
- 345
Yes, it is possible to count the number of sub-arrays in the array?
Here is example written in PHP
<?php
function getArrayCount(array $arr, $include_empty_arr = true, &$count = 0) {
foreach ($arr as $a) {
if (is_array($a)) {
$include_empty_array_flag = ($include_empty_arr) ? $include_empty_arr : (!empty($a));
if ($include_empty_array_flag) {
$count++;
}
getArrayCount($a, $include_empty_arr, $count);
}
}
return $count;
}
$my_arr = array(array('1', '2'), array('3', '4', array()), array('44', array(array(707, 808, 909, 180), 77, 88, 99, 100)), array('5', '6', '7', array('8', '9', '10', array())));
//if you want to count empty sub-array too, then simply call the function getArrayCount($my_arr);
echo "Number of sub-arrays : " . getArrayCount($my_arr);
//will output
//Number of sub-arrays : 9
//if you want to count sub-arrays which are not empty, then simply call the function getArrayCount($my_arr, false); with an additional boolean flag parameter
echo "<br/>Number of sub-arrays (exclude empty arrays) : " . getArrayCount($my_arr, false);
//will output
//Number of sub-arrays (exclude empty arrays) : 7
?>

- 101
- 1
- 3