Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,890 questions

51,817 answers

573 users

How to convert an int into an array of ints in C

3 Answers

0 votes
#include <stdio.h>

#define LEN 5
 
void convert_number(int arr[], int n) {
    for (int i = LEN - 1; i >= 0; i--) {
        arr[i] = n % 10;
        n = n / 10;
    }
}
 
int main(void)
{
    int arr[] = {0,0,0,0,0,0,0,0,0,0};
    int num = 78910;
    
    convert_number(arr, num);
 
    for (int i = 0; i < LEN; i++)
        printf("arr[%d] = %d\n", i, arr[i]);
        
    return 0;
}
 
 
 
 
/*
run:
       
arr[0] = 7
arr[1] = 8
arr[2] = 9
arr[3] = 1
arr[4] = 0
  
*/

 



answered Mar 21, 2016 by avibootz
edited Feb 2, 2024 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int* convert_number(int n, int size) {
    int* arr = (int*)malloc(size * sizeof(int));

    for (int i = size - 1; i >= 0; i--) {
        arr[i] = n % 10;
        n = n / 10;
    }

    return arr;
}

int main(void)
{
    int* arr = NULL;
    int num = 985710;

    int size = (int)log10(num) + 1;

    arr = convert_number(num, size);

    for (int i = 0; i < size; i++) {
        printf("arr[%d] = %d\n", i, arr[i]);
    }

    free(arr);

    return 0;
}




/*
run:

arr[0] = 9
arr[1] = 8
arr[2] = 5
arr[3] = 7
arr[4] = 1
arr[5] = 0

*/

 



answered Feb 2, 2024 by avibootz
edited Feb 2, 2024 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

void convert_number(int** arr, int n, int size) {
    *arr = (int*)malloc(size * sizeof(int));

    for (int i = size - 1; i >= 0; i--) {
        (*arr)[i] = n % 10;
        n = n / 10;
    }
}

int main(void)
{
    int* arr = NULL;
    int num = 985710;

    int size = (int)log10(num) + 1;

    convert_number(&arr, num, size);

    for (int i = 0; i < size; i++) {
        printf("arr[%d] = %d\n", i, arr[i]);
    }

    free(arr);

    return 0;
}




/*
run:

arr[0] = 9
arr[1] = 8
arr[2] = 5
arr[3] = 7
arr[4] = 1
arr[5] = 0

*/

 



answered Feb 2, 2024 by avibootz

Related questions

2 answers 191 views
2 answers 265 views
1 answer 169 views
2 answers 210 views
2 answers 189 views
4 answers 277 views
1 answer 107 views
...