Does anyone know how to find the length of an arbitrary type of array? All I have found online were how to find the length of an int array.
In my case I am trying to find the length of a string array.
sizeof(array) returns array size in bytes. sizeof(array[0]) returns size of single element in array. To get number of elements in array you must divide arrays's size by size of single element.
int arr_int[]={4,1,2,4,5};
sizeof(arr_int[0]) == sizeof(int) == 4 bytes sizeof(arr_int) == 20 bytes
20/4==5 elements in array
// bad
#define ARRAY_SIZE(array) (sizeof((array))/sizeof((array[0])))
// good
template <typename T,unsigned S>
inlineunsigned arraysize(const T (&v)[S]) { return S; }
int main()
{
// different kinds of arrays, all size 5
int normalarray[] = {1,2,3,4,5};
std::vector<int> vec(5);
int* dynamic = newint[5];
// ARRAY_SIZE will only work for normalarray:
cout << ARRAY_SIZE(normalarray); // prints 5 as expected
cout << ARRAY_SIZE(vec); // prints unreliable garbage
cout << ARRAY_SIZE(dynamic); // prints unreliable garbage
// on the other hand, arraysize will give you an error if you use it incorrectly:
cout << arraysize(normalarray); // prints 5 as expected
cout << arraysize(vec); // gives you a compiler error
cout << arraysize(dynamic); // gives you a compiler error
}
typedefint int5[5]; // int5 foo; is now the same as int foo[5];
void func(const int5& v) // the typedef makes this easier to understand
{
// a function that takes an array of 5 ints by reference
}
int main()
{
int four[4];
int five[5];
int six[6];
func(four); // error int[4] is not int[5]
func(five); // OK
func(six ); // error int[6] is not int[5]
int* dynamic = newint[5];
func(dynamic); // error, int* is not the same as int[5]
}
The int5 typedef makes the function easier to understand, but you can do it without the typedef:
1 2 3 4
void func(constint (&v)[5])
{
// same thing as above
}
If you template it, the function can accept arrays of any size:
template <unsigned S>
void func(int (&v)[S])
{
cout << S;
}
int main()
{
int four[4];
int five[5];
// verbose, specifying the size in the <template args>
func<4>(four); // prints "4"
func<5>(five); // prints "5"
// if you leave out the <args>, the compiler will try to
// determine the args based on whatever type you give it
func(four); // prints "4" because we're passing an int[4] -- the compiler
// can figure out that the size is 4 and set 'S' accordingly
}
All I do from there is just template the type as well, so it can work with arrays of any type instead of just arrays of ints.