looking for a pre-built function to compute the num of elements in an array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • momotaro
    Contributor
    • Sep 2006
    • 357

    looking for a pre-built function to compute the num of elements in an array

    N.B my array is of a user defined type containing multiple fields

    thx
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    There isn't one in C. A macro I have seen used quite a lot is

    Code:
    #define ARRAY_LEN(a)  ((sizeof (a))/(sizeof (a)[0]))
    But that only works on actual arrays not pointers to arrays.

    Of course if you are using C++ you should not be using an array but a vector which would give the result through the size() member function.

    Comment

    • scruggsy
      New Member
      • Mar 2007
      • 147

      #3
      Assuming the array is not dynamically allocated, use the sizeof operator.
      Code:
      struct Thing
      {
        int a;
        int b;
      };
      
      Thing things[5];
      Assuming a Thing occupies 8 bytes, sizeof(Thing) is 8.
      sizeof(things) is the size of each element times the number of elements: 5 * 8.
      You can't pass the array to a function and use sizeof on it. You can however use a macro.
      Code:
      #define ARR_SIZE(ARR, ELEM) (sizeof( (ARR) ) / (sizeof( ( ELEM ) ) ) )

      Comment

      • RRick
        Recognized Expert Contributor
        • Feb 2007
        • 463

        #4
        I'm with Banfa, you should be using a STL vector.

        The main reason is that dynamically allocated data is the norm, not the exception. With that data, there is no runtime way to calculate the size unless you yourself have defined some last element delimiter. In a char *, this is the null char, and usually in arrays, a null pointer follows the last valid pointer.

        Its easier to let the vector object deal with these issues.

        Comment

        Working...