-1

Im learning C right now and I've got this problem I want to convert the integer into an array my code works but the problem is that I declare the size of an array in the beginning and I want to make it so that it works for every integer basically.

#include<stdio.h>
int main()
{
    int x,i,temp;
    int arr1[6];
    scanf("%d",&x);
    for (i=5;i>=0;i--){
        temp=x%10;
        arr1[i]=temp;
        x/=10;
    }
    
    for (i=0;i<=5;i++){
        printf("%d",arr1[i]);
    }
    
    return 0;
}

Can you please help me?

I'm trying to find solution for the problem.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Giorgi
  • 13
  • 2
  • 1
    No integer under any C compiler you're likely to use will have more than 20 digits. – Steve Summit Feb 05 '23 at 20:34
  • There are techniques for dynamically growing an array to as big as it needs to be, even if you have no way of knowing in advance, but I think they're overkill in this case. – Steve Summit Feb 05 '23 at 20:35
  • If you want to try to compute it in advance, the number of digits in a number `x` is approximately `log10(x)`. – Steve Summit Feb 05 '23 at 20:37
  • 1
    Is this an [XY problem?](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) Normally, if you want to examine the digits of a "number" you will input it as string. Which is what you do anyway: you type it digit by digit and it's perverse to tell the language to convert it to an integer, and then laboriously unpick it. – Weather Vane Feb 05 '23 at 20:37
  • Thanks for all the advices i'll try them out and see how it goes. :D – Giorgi Feb 06 '23 at 21:28

1 Answers1

0

For starters your code does not take into account that the user can enter a negative number.

If you are not going to deal with negative values then declare the variable x as having an unsigned integer type as for example unsigned int.

As for your problem then you can use a variable length array.

For example

#include <stdio.h>

int main( void )
{
    unsigned int x;

    if ( scanf( "%u", &x ) == 1 )
    {
        size_t n = 0;
        unsigned int tmp = x;

        do 
        {
            ++n;
        } while ( tmp /= 10 );

        unsigned int a[n];

        for ( size_t i = n; i != 0; x /= 10 )
        {
            a[--i] = x % 10; 
        }

        for ( size_t i = 0; i < n; i++ )
        {
            printf( "%u ", a[i] );
        }
        putchar( '\n' );
    }
}

If your compiler does not support variable length arrays then you can allocate an array dynamically using standard function malloc declared in header <stdlib.h> as for example

unsigned int *a = malloc( n * sizeof( *a ) );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335