so I've been trying to write this piece of code in c where the basic idea is that the user enters a positive integer and the program prints the digits in that number, and I've done it recursively but the thing is, when I compile it, I get no errors but the output is just some trash, on the other hand, I've tried debugging and so I've set some breakpoints and I keep getting fine results all the way and correct output while debugging, unlike when trying to compile the exact same piece of code If anyone has any idea why this is so, it would be really appreciated
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *numToWord (int number){
char *newDigit = NULL;
switch(number){
case 0:
newDigit = malloc (5*sizeof(char));
sprintf(newDigit,"zero");
break;
case 1:
newDigit = malloc (4*sizeof(char));
sprintf(newDigit,"one");
break;
case 2:
newDigit = malloc (4*sizeof(char));
sprintf(newDigit,"two");
break;
case 3:
newDigit = malloc (6*sizeof(char));
sprintf(newDigit,"three");
break;
case 4:
newDigit = malloc (5*sizeof(char));
sprintf(newDigit,"four");
break;
case 5:
newDigit = malloc (5*sizeof(char));
sprintf(newDigit,"five");
break;
case 6:
newDigit = malloc (4*sizeof(char));
sprintf(newDigit,"six");
break;
case 7:
newDigit = malloc (6*sizeof(char));
sprintf(newDigit,"seven");
break;
case 8:
newDigit = malloc (6*sizeof(char));
sprintf(newDigit,"eight");
break;
case 9:
newDigit = malloc (5*sizeof(char));
sprintf(newDigit,"nine");
break;
}
return newDigit;
}
char * writeAbsolute (int number) {
char * word = NULL; // variable where the return value will be stored, must clean in main part
int digit;
digit = number % 10;
if (number){
number /= 10;
word = writeAbsolute (number);
char *newDigit = NULL;
char *newWord = NULL;
newDigit = numToWord(digit);
if (word){
int numOfLetters = (int)( strlen(newDigit)+strlen(word) );
newWord = (char*) malloc(numOfLetters * sizeof(char));
sprintf(newWord,"%s %s",word,newDigit);
word = newWord;
}
else{
word = newDigit;
}
free (newWord);
free (newDigit);
}
return word;
}
int main() {
int number;
char * word;
printf("Enter an integer:\n");
scanf("%d",&number);
word = writeAbsolute(number);
printf("%s",word);
return 0;
}