I'm a beginner in C, I wanted to write a program that converts user input into Morse code. This is what I did:
char morseCode[26][4] = {
".-", /* A */
"-..", /* B */
"-.-.", /* C* */
"-..", /* D */
".", /* E */
"..-.", /* F* */
"--.", /* G */
"....", /* H* */
"..", /* I */
".---", /* J */
"-.-", /* K */
".-..", /* L* */
"--", /* M */
"-.", /* N */
"---", /* O */
".--.", /* P* */
"--.-", /* Q* */
".-.", /* R */
"...", /* S */
"-", /* T */
"..-", /* U */
"...-", /* V* */
".--", /* W */
"-..-", /* X* */
"-.--", /* Y* */
"--.." /* Z */
};
char uString[100], newString[100];
int uChoice;
int main(){
//printf("morseCode[%d] = %s\n", 2, morseCode[2]);
printf("Enter text (max 100 characters): ");
fgets(uString, 100, stdin);
printf("\nString in morse code: \n");
for (int i = 0; i < strlen(uString); i++) {
uString[i] = toupper(uString[i]);
newString[i] = uString[i] - 'A';
printf("newString[%d] = %d\tmorseCode[newString[%d]] = %s\n", i, newString[i], i, morseCode[newString[i]]);
}
return 0;
}
Notice I placed a * in the comments where I was facing output errors. This is what it looked like when I printed it out: imgur
I looked online for solutions and I found someone who did the same thing, but he declared his version of "morseCode" like this:
char *morseCode[] = {/* Strings here*/};
When I did this, everything worked perfectly and outputted exactly as expected.
Why does making morseCode a pointer fix these issues? I thought any array with a char datatype would immediately become a pointer anyway? Is this just a best practice I should do all the time?