I'm trying to find the length of any given array and the methods I've tried so far won't work. This is my sizeOf function (not to be confused with sizeof):
template <typename T>
size_t sizeOf(T val) {
size_t sz = (size_t)0;
if (typeid(val).name()[0] == 'c') {
sz = (int)sizeof(val);
} else if (typeid(val).name()[1] == 'c' || typeid(val).name()[2] == 'c'){
sz = strlen((const char*)val);
} else if (typeid(val).name()[0] == 'i') {
sz = sizeof(val) / 4;
} else {
sz = 0; //new code here.
}
return sz;
}
So far, it works for strings, integers, and characters. The problem is finding the length of any array that isn't of type char
. I tried using a for loop and subscripted values (e.g. arr[i]
), but this exception occurs when the argument isn't an array: subscripted value is neither an array nor pointer
. To this I try a try {...} catch () {...}
statement and it still gives this error, so I can't use indices. I also tried another method with pointers: *(&arr + 1) - arr
which works without errors, but the values are inconsistent or completely imprecise. Is there a way to acquire the true length of an array without the aforementioned methods and still have a flexible function?