May 7, 2013 at 3:16am UTC
Hi, I have a doubt, and wanted to clarify something. Can I get the logical size of an array by doing this:
1 2 3 4 5 6
double getLogicalSize( char a[] )
{
int x;
for ( x = 0; a[x] != '\0' ; x++ );
return x;
}
Last edited on May 7, 2013 at 3:17am UTC
May 7, 2013 at 11:10am UTC
It won't work for all arrays, because arrays don't automatically end with '\0'.
This is the thing I use:
1 2 3 4 5
template < typename T, int size >
std::size_t arraySize( const T ( &array ) [ size ] )
{
return ( size );
}
And you can use it like this:
1 2 3 4
int array[ 50 ];
double array2[ 560 ];
std::cout << arraySize( array ) << ' ' << arraySize( array2 ) << std::endl;
Last edited on May 7, 2013 at 11:10am UTC
May 7, 2013 at 11:18am UTC
It is not clear why you are returning double because "logical size of an array" usually is unsigned int.:)
What you are trying to do is already done and named as std::strlen that is declared in header <cstring> .:)
Last edited on May 7, 2013 at 11:19am UTC
May 7, 2013 at 12:46pm UTC
You return x(int), but function must return double because you write double getLogicalSize( char a[] )
May 7, 2013 at 12:54pm UTC
@amchinese
If you return an integer from a function with return type double, the integer will automatically be converted to a double.
May 7, 2013 at 8:04pm UTC
I will change it to int function then.
and vlad from moscow I forgot to meantion I cannot use strlen
Fransje isnt your code return the physical size only?? because sometimes an array may not be loaded completly, so thats the size I want to get
May 9, 2013 at 6:26pm UTC
You could always use a vector then and get the size of that?
and why not just use the function .size() or .length() you can use that on strings, arrays, vectors ect.