View Single Post
Join Date: May 2005
Posts: 232
Reputation: Dogtree is an unknown quantity at this point 
Solved Threads: 3
Dogtree's Avatar
Dogtree Dogtree is offline Offline
Posting Whiz in Training

Re: get length of a dynamic array

 
0
  #7
Jun 1st, 2005
>> The easiest way to get the length of a dynamic array is this
Is it? Forget about the 'array' part and look closely at the 'dynamic' part. A dynamic array is not an array, it's a pointer to a block of memory that can be subscripted like an array:
  1. #include <iostream>
  2.  
  3. #define length(x) (sizeof(x) / sizeof(*(x)))
  4.  
  5. void foo(int a[])
  6. {
  7. std::cout << "From foo(): " << length(a) << '\n';
  8. }
  9.  
  10. int main()
  11. {
  12. int *a = new int[10];
  13. int b[10];
  14.  
  15. std::cout << "From main(): " << length(a) << '\n';
  16. foo(b);
  17. }
So the sizeof trick just breaks silently when you use it on a dynamic array, or an array passed as a function parameter. Templates are a better solution because they complain when you pass a pointer and not an array:
  1. #include <iostream>
  2.  
  3. template <typename T, int sz>
  4. char (&array(T(&)[sz]))[sz];
  5.  
  6. void foo(int a[])
  7. {
  8. std::cout << "From foo(): " << sizeof array(a) << '\n';
  9. }
  10.  
  11. int main()
  12. {
  13. int *a = new int[10];
  14. int b[10];
  15.  
  16. std::cout << "From main(): " << sizeof array(a) << '\n';
  17. foo(b);
  18. }
The rule of thumb is that if you want the size of a dynamic array, you save it! If you want the size of an array parameter, you pass it! Anyone who doesn't know these rules or isn't comfortable with them would be better off using a smart container like std::vector or boost::array.
Reply With Quote