0

I'm working on my Load function in Pset5, and my current error seems to be the result of the strcmp not working as I expected.

for(int i = 0; strcmp(&c, "\n") != 0; i++)

In GDB I can see that c = "\n", and yet the comparison is returning 1 rather than 0.

I've pasted the rest of the code below for context.

// define node structure
typedef struct node
{
    bool is_true;
    struct node* children[27];
} node;

// initialize first node
node* trie = malloc(sizeof(node));
node* node_ptr = trie;
int index;

// iterate through the dictionary one char at a time
for(char c = fgetc(file); c != EOF; c = fgetc(file))
{
    // for each word
    for(int i = 0; strcmp(&c, "\n") != 0; i++)
    {
        // converts character to corresponding key number
        if(strcmp(&c, "\'") == 0)
            index = 26;
        else
            index = tolower(c) - 'a';

        if(node_ptr->children[index] == NULL)
        {
            // malloc a new node
            node* new_node = malloc(sizeof(node));

            // set pointer to new node
            node_ptr->children[index] = new_node;

        }
        else
        // set pointer to new node
        node_ptr = node_ptr->children[index];

        // advance reader
        c = fgetc(file);
    }

    // End of word, set bool value to TRUE
    node_ptr->is_true = true;

    // advance reader
    c = fgetc(file);
}
return true;
1
  • Manage to work around this by initializing c as an int instead of a char - but I'd still be curious why it wouldn't work the other way.
    – Jon Levin
    Commented Dec 2, 2015 at 17:50

1 Answer 1

1

The first thing I see is that you are comparing a string, "\n" to a char, the contents of c. This is usually bad.

Instead of that, have you considered just checking the equality of two chars, c == '\n' ? Note the single quotes to indicate a char, not double quotes indicating a string.

If this answers your question, please click the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .