Thanks! Works perfectly now. Java has made me stupid 🙁
I am having some difficulty comparing strings in C. I get correct output when I don’t use my isMorse function, but when I use it the output becomes inaccurate and displays random characters. As far as I can tell, the variable “morse” is actually changed when strcmp is called on it. I am thinking that it has to do with “morse” not being a constant, but I am unsure of how to remedy it.
Thanks!!
char *EnglishToMorse(char english)
{
static char *morse;
int i;
for (i = 0; i < LOOKUP_SIZE; i++)
{
if (lookup[i].character == english)
{
morse = lookup[i].morse;
return morse;
}
}
morse = &english; // Problem was here!!!
return morse;
}
The reason your
morsevariable appears to change is because it points to an area on the stack. The reason it points to an area on the stack is because you assigned it the address of your parameterenglish, which got pushed onto the stack when you called your function then popped off the stack once the function completed.Now your morse variable will point to whatever memory takes that same location on the stack, which will constantly change throughout the lifetime of your program.
In my opinion, the best way to fix this problem would be to return a NULL pointer from
EnglishToMorseif the character is not A-Z… then check for the NULL pointer in yourisMorsefunction. After all, it’s good practice to check for NULL pointers in code.