简体   繁体   中英

Using char *s and strcmp function in c++

I have two char* references and I am trying to figure out which one is less. The code I have is:

bool stringComparison::lessThan(char *s1, char* s2) {
  int result = strcmp(*s1,*s2);
  return result < 0;
};

the result is not producing less than 0 ever. How do I need to change the "int result" line to make this work?

thanks

strcmp is used to compare strings; *s1 and *s2 are characters. You should be calling strcmp with s1 and s2 (no stars).

EDIT:

Here is the reference for strcmp

s1 and s2 are strings. So your code

int result = strcmp(*s1,*s2);

should read

int result = strcmp(s1,s2);

See the on-line reference for strcmp .

You have more problems, or different problems, than what you've told us.

In the code you've shown us, the s1 and s2 parameters are of type char* . The strcmp() function expects arguments of type char* (actually const char* ).

If you call strcmp(*s1,*s2) , that's an attempt to call strcmp with two arguments of type char . That won't give you incorrect results as you describe; it won't compile. At the very least, your compiler should be complaining about type mismatches.

If you don't have a #include for either <string.h> or <cstring> , the header that declares the strcmp function, then it's possible that the compiler won't recognize the mismatch -- but calling an undeclared function is invalid in C++.

It's true, as both of the other answers say, that you should be calling strcmp(s1, s2) rather than strcmp(*s1, *s2) -- but that doesn't explain the symptoms you're describing. Correcting the call to strcmp() will not by itself correct all the problems you're having.

I can think of a few possible explanations:

  1. You're using an old compiler that doesn't complain about calls to undeclared functions. Get a newer compiler, or invoke your compiler with options that make it conform more closely to the language standard.

  2. Your compiler is producing warnings (diagnostics don't have to be fatal) and you're ignoring them. Don't ignore warnings.

  3. For some reason, you've decided to add your own declaration of the strcmp() function, perhaps something like int strcmp(char s1, char s2); . Don't do that. If you need a declaration for a standard function, add a #include directive for the appropriate header.

Can I suggest a (possibly) improved version of your function? This fixes the call to strcmp , removes the unneeded result variable, and adds const-correctness.

bool stringComparison::lessThan(const char *s1, const char *s2)
{
    return strcmp(s1, s2) < 0;
}

If stringComparison is a class I'd add another const to the end of the function definition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM