Logical Size of Array

May 7, 2013 at 3:16am
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
May 7, 2013 at 6:46am
try it... lol
May 7, 2013 at 11:10am
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 May 7, 2013 at 11:10am
May 7, 2013 at 11:18am
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
May 7, 2013 at 12:46pm
You return x(int), but function must return double because you write double getLogicalSize( char a[] )
May 7, 2013 at 12:54pm
@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
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 7, 2013 at 8:14pm
Fransje isnt your code return the physical size only??

Yeah, it is. I misunderstood your question :)
May 9, 2013 at 6:26pm
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.