Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <malloc.h>
- #include <math.h>
- int main()
- {
- int tamanho = 0;
- int numero = 589;
- int num = numero;
- //obtenho o tamanho do numero com divisoes sucessivas por 10
- for( ; num != 0; num=num/10,tamanho++);
- //aloco um ponteiro para char, definido pelo tamanho * tamanho de 1 char
- char *numeroString = (char *)malloc(tamanho * sizeof(char));
- /*
- * neste ponto gravo o inteiro no char da seguinte forma:
- *
- * numero = 213
- * num = 213 / 100 = 2 (resultado truncado)
- * numero = 213 % 100 = 13
- *
- * num = 13 / 10 = 1
- * numero = 13 % 10 = 3
- *
- * num = 3 / 1 = 3
- * numero = 3 % 1 = 0
- */
- for(int i=tamanho; i>=1; i--)
- {
- int pot = pow(10,i-1);
- int num = numero / pot;
- numero = numero % pot;
- *(numeroString + (tamanho-i) ) = (char)(num+48);
- }
- //percorro meu 'vetor'
- for(int i=0; *(numeroString+i) != '\0'; i++)
- {
- printf("String: %c\n",*(numeroString+i));
- }
- //libero a memoria
- free(numeroString);
- /*
- * se estas executando em um terminal, use a seguinte linha para compilar:
- * gcc -std=c99 -lm po.c -o po
- */
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement