C Strings Comparison with Equal Sign

后端 未结 5 595
借酒劲吻你
借酒劲吻你 2020-11-29 12:45

I have this code:

char *name = \"George\"

if(name == \"George\")
   printf(\"It\'s George\")

I thought that c strings could not be compare

相关标签:
5条回答
  • 2020-11-29 12:58

    If you compare two stings that you are comparing base addresses of those strings not actual characters in those strings. for comparing strings use strcmp() and strcasecmp() library functions or write program like this. below is not a full code just logic required for string comparison.

    void mystrcmp(const char *source,char *dest)
    {
        for(i=0;source[i] != '\0';i++)
            dest[i] = source[i];
       dest[i] = 0;
    
    }
    
    0 讨论(0)
  • 2020-11-29 12:59

    This will fail, since you are comparing two different pointers of two separate strings. If this code still works, then this is a result of a heavy optimization of GCC, that keeps only one copy for size optimization.

    Use strcmp(). Link.

    0 讨论(0)
  • 2020-11-29 13:01

    Just to provide a reference to @H2CO3's answer:

    C11 6.4.5 String literals

    It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

    This means that in your example, name(a string literal "George") and "George" may and may not share the same location, it's up to the implementation. So don't count on this, it may results differently in other machines.

    0 讨论(0)
  • 2020-11-29 13:10

    I thought that c strings could not be compared with == sign and I have to use strcmp

    Right.

    I though that this was wrong because it is like comparing pointers so I searched in google and many people say that it's wrong and comparing with == can't be done

    That's right too.

    So why this comparing method works ?

    It doesn't "work". It only appears to be working.

    The reason why this happens is probably a compiler optimization: the two string literals are identical, so the compiler really generates only one instance of them, and uses that very same pointer/array whenever the string literal is referenced.

    0 讨论(0)
  • 2020-11-29 13:18

    The comparison you have done compares the location of the two strings, rather than their content. It just so happens that your compiler decided to only create one string literal containing the characters "George". This means that the location of the string stored in name and the location of the second "George" are the same, so the comparison returns non-zero.

    The compiler is not required to do this, however - it could just as easily create two different string literals, with different locations but the same content, and the comparison would then return zero.

    0 讨论(0)
提交回复
热议问题