The function has undefined behavior because it returns nothing when the number is not positive.
And for a two-digit number the function returns 1 because the expression can yield 1.
number=number/10;
It can look the following way
size_t intLength( int number )
{
const int Base = 10;
size_t n = 0;
do
{
++n;
} while ( number /= Base );
return n;
}
As for your question then you may not initialize a variable length array.
From the C Standard(6.7.9 Initialization)
3 The type of the entity to be initialized shall be an array of
unknown size or a complete object type that is not a variable length
array type.
So this variable length array declaration with an initializer
char string[intLength(number)]={0};
is incorrect.
Instead you can use the standard C function memset
declared in the header <string.h>
.
Here is a demonstrative program.
#include <stdio.h>
#include <string.h>
size_t intLength( int number )
{
const int Base = 10;
size_t n = 0;
do
{
++n;
} while ( number /= Base );
return n;
}
int main(void)
{
char string[intLength( 241 ) + 1];
printf( "The size of the string is %zu\n", sizeof( string ) );
memset( string, 0, sizeof( string ) );
return 0;
}
The program output is
The size of the string is 4
In the declaration
char string[intLength( 241 ) + 1];
I added one more character for the terminating zero
'\0'
provided that the character array will indeed contain a string.