Home > Net >  How to compare a string* and const char* in an if statement?
How to compare a string* and const char* in an if statement?

Time:10-12

I am trying to compare a string* to a const char* in an if statement. The string pointer is apart of a class called HashNode (a node for a hash table implemented with Linear Probing). I am trying to set the node's status to "never used", "tombstone", or "occupied". My code, which is throwing errors, is as follows:

while (table[slot]->status != "never used"){
    // if the node is found, return true
    if(table[slot]->word == word) return true ;
    // increment index and wrap back around the table
    slot = (slot   1) % TableSlots ;
}

My HashNode class is defined as:

class HashNode{
public:
    string *word ;
    const char *status ;

    // Basic constructor for a node
    HashNode(string word, string status) {
        // this keyword references the key and word variables which belong to the class
        this->word = &word ;
        this->status = status ;
    }
} ;

I have changed the status declaration in HashNode to const char* to try and remove this error, but how would I get around the following:

error: invalid operands to binary expression
('std::__1::string *' (aka 'basic_string<char, char_traits<char>,
allocator<char> > *') and 'std::__1::string' (aka 'basic_string<char,
char_traits<char>, allocator<char> >'))
if(table[slot]->word == word) return true ;

CodePudding user response:

you cant just do == operator on char*, you have to use strcmp() for it,

like ...

strcmp( table[slot]->status,"never used" ) != 0 

and you also have to dereference the string before you can invoke == operator on string...

*table[slot]->word == word

CodePudding user response:

The error is complaining about comparing a pointer to a nonpointer. Deference the pointer first:

if(*(table[slot]->word) == word) return true ;
  •  Tags:  
  • c
  • Related