I want to convert integer into an array in C and this is my code and it kind of works

70 Views Asked by At

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.

1

There are 1 best solutions below

0
Vlad from Moscow On BEST ANSWER

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 ) );