How to get number of elements in the array of pointers?

  • A+

How to get number of elements in array of pointers?

Below is my code:

struct mystruct      {       int a;       char ch[10];       int c;     };  mystruct *m_arr[2]; 

I am traversing this array in some other files. Instead of hard-coding as 2 in every file I want to get the number of elements in the array programmatically.


Don't use raw arrays. Use a standard container like std::vector or std::array. Both of these have a .size() member, and allow the range-based for syntax:

    for (mystruct* p : m_arr) 

If you need C compatability, they both offer a data() member function which returns a pointer to the first element in the underlying array. (In your case, that will be a mystruct **)

Edit: A raw array also supports the range-based for syntax - but only if the visible declaration includes the number of elements (so my_struct* m_arr[2]; is fine, but my_struct* m_arr[] would not work). It is impossible to declare a std::array without defining the size too. Other containers (like std::vector) don't include the size in the declaration.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: