user3440111
user3440111

Reputation: 5

Searchin in a stack

This is my code for the searching part and it's not working. Can you give me a little help on this? I'm newbie on programming and I really just suck at pointers. Thanks.

typedef struct Dictionary_Entry{
    int index;
    char character[100];
    struct Dictionary_Entry *link;
}Dictionary_Entry;

typedef struct Dictionary{
    Dictionary_Entry *top;
}Dictionary;

int check_in_dictionary(Dictionary *dictionary, char string[100], char file_char[100]){
    Dictionary_Entry *runner = dictionary->top;
    strcat(string, file_char);
        while(runner != NULL){
            if((strcmp(string, runner->character)) == 0){
                break;
                return runner->index;
            }
        }
        return -1;
}

Upvotes: 0

Views: 54

Answers (3)

Jabberwocky
Jabberwocky

Reputation: 50831

Here is the corrected version with my comments starting with ////

int check_in_dictionary(Dictionary *dictionary, char string[100], char file_char[100]){
    Dictionary_Entry *runner = dictionary->top;
    strcat(string, file_char);
    while(runner != NULL){
      if((strcmp(string, runner->character)) == 0){
         return runner->index;  // found
         //// break not neccessary here as return returns anyway
      }
      runner = runner->link ;  //// goto next entry
    }
    return -1;
}

BTW strcat(string, file_char); is not necessary, you could compare directy to file_char like this strcmp(file_char, runner->character)

Upvotes: 1

Vittorio
Vittorio

Reputation: 11

You need to scan the Dictionay in while loop. something like this:

 while(runner != NULL){
        if((strcmp(string, runner->character)) == 0){
            return runner->index;
        }
    runner = runner->next; /* go to next element in dictionary */
    }

Upvotes: 0

John C
John C

Reputation: 1981

The break keyword leaves the loop, so your return runner->index line doesn't get executed. Swap the two lines (or remove break, since return will also leave the loop, in its way), and you should be fine.

Upvotes: 2

Related Questions