If you know for certain that it is a stack allocated array object and not a pointer i.e. declared like
and that it is not just a pointer to some block of memory (char*, int*, double*, etc.), then you can write a small template function that will tell you the size of the array. Something like this should do it:Code:char arr1[15]; int arr2[32]; double arr3[80]; //etc...
The usage being something along the lines of (using the previously defined stack array code in this post):Code:template <typename T, size_t U> size_t size(T (&arr)[U]) { return sizeof(arr)/sizeof(arr[0]); }
However, the above only works on stack allocated arrays, not pointers. If you have a char* pointer to some NULL termintated piece of memory, then you can get the size with this function:Code:std::cout << size(arr1) << std::endl; // prints 15 std::cout << size(arr2) << std::endl; // prints 32 std::cout << size(arr3) << std::endl; // prints 80
The usage being along the lines ofCode:size_t size(std::string s) { return s.size(); }
If you have a pointer to any other type of array, then it is not wise to assume a termination condition even if you think you can control it, you should/must record the size of the array at it's creation time.Code:const char* str = "Hello world!"; std::cout << size(str) << std::endl; //prints 12
That said, I agree with the suggestion to use a proper container instead of arrays.




Reply With Quote
