0

but it isn't possible because I can't put a variable in the array size. ideas? the function will check how many digits build the integer and will return that number

int intLength(int number)
{
    for(int i=0;i<number;i++)
    {
        number=number/10;
        if(number==1||number==0)
        {
            return i;
        }
    }
}

void just_a_function(void)
{
    number=241;
    char string[intLength(number)]={0};
}
abelenky
  • 63,815
  • 23
  • 109
  • 159
G0rdo1
  • 73
  • 1
  • 1
  • 6

2 Answers2

3

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
2

You are asking for a Variable Length Array (VLA).

VLAs cannot be initialized with the = {}; syntax, since the compiler does not know at compile-time how much space to initialize.

Instead, use memset:

void just_a_function(void)
{
    number=241;
    char string[intLength(number)];        // Declare a VLA
    memset(string, 0, intLength(number));  // Set it to empty/zero
}

If your compiler does not support VLAs, then you would use malloc instead:

void just_a_function(void)
{
    number=241;
    char* string = malloc(intLength(number)+1);
    string[0]='2';
    string[1]='4';
    string[2]='1';
    string[3]='\0';
    free(string);
}
abelenky
  • 63,815
  • 23
  • 109
  • 159