c - How to get number of arrays in a multidimensional array -


i have multidimensional array consisting of several sub arrays. possible count number of sub-arrays in array?

if array declared on stack, can number of elements using sizeof() function:

#include <stdio.h> #include <stdlib.h>  int main() {     int a[3][4];      fprintf(stdout, "size of 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 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, modify denominator sizes of elements @ different dimension indices. i'll leave exercise.

now, if array declared dynamically — on heap — cannot use technique.

you create struct mimic vector, stores pointers, along size_t representing number of elements. extend idea keep vector of vectors, or vector of vectors of vectors, , on. getting number of "subarrays" matter of looking size parameter of each nested vector , keeping running tally.


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

node.js - How to abort query on demand using Neo4j drivers -