Link to home
Start Free TrialLog in
Avatar of tam031198
tam031198

asked on

How to get the size of an array in a function

I have an array of a structure and this array is passed by reference to a function.  What do I have to do to know how many element does the array have ?  

I know usually, we pass the array size as parameter too but is it possible to figure it out ?

Here is how my code look like !

       struct TEST
       {
             int a;
             int b;
             int c;
             bool d;
       };

       void main()
       {
            void F1(TEST *);    

             TEST TstArray[10];
              F1(TstArray);
       }    

       void F1(TEST *TstArray)
       {
           // Here, what do I have to do to know how many element does the TstArray have ????
       }
ASKER CERTIFIED SOLUTION
Avatar of nietod
nietod

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You have to pass the array size to the function as well.
Avatar of nietod
nietod

It is best to pass the array size as a parameter or to use some sort of semaphore value that indicates that it is the last item in the array.  In general, it is not possible to determine the size of an array given a pointer to it.

However, if you know that the array is dynamically allocated and if you know that the pointer you have points to the start of the array, then you can use _msize() do determine the amount of memory allocated for the array. You can divide this by the size of the array elements to get the number of items in the array.  However, I do not recommend this tecnhique  The two conditions that it relies upon tend to be too restrictive and eventually some code will violate those restrictions and you will have a bug.  

Pass a size or use a semaphore.
Avatar of tam031198

ASKER

Thank you very much !