Logical Size of Array

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
try it... lol
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;


50 560
Last edited on
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
You return x(int), but function must return double because you write double getLogicalSize( char a[] )
@amchinese
If you return an integer from a function with return type double, the integer will automatically be converted to a double.
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
Fransje isnt your code return the physical size only??

Yeah, it is. I misunderstood your question :)
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.
Topic archived. No new replies allowed.