I'm trying to modify a string and then return it in C. But the code doesn't work well. When I run the function in main, the wordOfNum returns an empty string
Here's the code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
char *wordOfNum(int number, int spec) {
char *word = malloc(strlen("Example") + 1);
if (spec == 0) {
switch (number) {
case 1:
strcpy(word, "one");
break;
case 2:
strcpy(word, "two");
break;
case 3:
strcpy(word, "three");
break;
case 4:
strcpy(word, "four");
break;
case 5:
strcpy(word, "five");
break;
case 6:
strcpy(word, "six");
break;
case 7:
strcpy(word, "seven");
break;
case 8:
strcpy(word, "eight");
break;
case 9:
strcpy(word, "nine");
break;
}
}
else if (spec == 1) {
switch (number) {
// case 1: return "one";
case 2:
strcpy(word, "twenty");
break;
case 3:
strcpy(word, "thirty");
break;
case 4:
strcpy(word, "fourty");
break;
case 5:
strcpy(word, "fifty");
break;
case 6:
strcpy(word, "sixty");
break;
case 7:
strcpy(word, "seventy");
break;
case 8:
strcpy(word, "eightty");
break;
case 9:
strcpy(word, "ninety");
break;
}
}
return word;
}
void exercise1() {
char num[4];
printf("This is exercise 1: \n");
printf("Enter a 4 digit number: ");
scanf("%[^\n]%*c", num);
printf("%s thoundsand %s hundred %s %s", wordOfNum(num[0], 0), wordOfNum(num[1], 0), wordOfNum(num[2], 1), wordOfNum(num[3], 0));
}
int main() {
exercise1();
return 0;
}
I think the problem is about scoping. At wordOfNum I'm using a switch nested in an if so the word doesn't change as supposed. When I strcpy word 1 level up, which means only in a single if, the word can change