user1827962
user1827962

Reputation: 11

String Compare not working in C

I have a function in my program that is supposed to take Morse code input, compare it to an array of strings and return a letter from a corresponding string once it has found the matching Morse. I've finally managed to get it to run without crashing, but now it keeps returning the wrong letters. For instance ... --- ... should return sos but instead I get amb. I tried testing it by printing out the index number, the morse code string and the letter and it all matched up, so I think the problem is with string compare.

Here's the code:

void morsetotext(char mor[])
{
     char alpha[]={"abcdefghijklmnopqrstuvwxyz1234567890 "};
     char *morse[] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", 
     "..", ".---","-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", 
     "...", "-", "..-", "...-",".--", "-..-", "-.--", "--.","-----", ".----", 
     "..---", "...--", "....-",".....", "-....", "--...", "---..", "----." "/ "};
     char letter[8];
     char convert[250];
     int con_count=0;
     int let_count=0;
     int count=0;
     int index=0;
     int length=strlen(mor);

     while (count<length)
     {
           for(let_count=0; let_count<8 && mor[count]!=' '; let_count++)
           {
                            letter[let_count]=mor[count];
                            count++;
           }

           letter[let_count+1]='\0';

           index=0;
           while (strcmp (letter, morse[index])!=1)
           {
                 index++;
           }

           count++;

           printf ("%c", alpha[index]);
     } 
     return;
}

Thanks for any help.

Edit: Sorry about that, here's the whole function.

Upvotes: 1

Views: 913

Answers (3)

abelenky
abelenky

Reputation: 64730

This statement:

letter[let_count+1]='\0';

is writing to letter[9] if the input (mor) is 8 characters long.

You declared letter as char letter[8];, so the only valid indicies are [0] - [7].

Assigning to letter[9] is most likely causing the seg-fault you describe.

It seems to me that you want letter to contain up to 8 data characters, plus one null-terminator (\0). That suggests you should declare it as char letter[9];.

Upvotes: 1

JvO
JvO

Reputation: 3106

Compare strcmp() against 0, not 1. the function will only return 0 with a full match. Read the manual! :)

Upvotes: 5

cnicutar
cnicutar

Reputation: 182744

while (strcmp (letter, morse[index])!=1)

You probably meant 0 instead of 1. Or just say while (!strcmp(...)).

Upvotes: 5

Related Questions