Understanding Char Array equality in C

后端 未结 5 873
忘了有多久
忘了有多久 2021-01-19 13:47

Sorry in advance for the ignorance. I don\'t fully understand how to compare char arrays in C. I was originally comparing two char arrays in c with the simple ==

5条回答
  •  感情败类
    2021-01-19 14:50

    if (a == b)
    

    Here you are comparing pointers and not the strings

    strcmp(a, b)
    

    Here you are comparing strings

    Which one is correct and why? What is the other one doing?
    

    Since there are 2 strings stored in different memory locations or if the same string is being stored there is possibility a==b comparing pointers doesn't make sense.What you want is to compare the contents of the locations the pointers are pointing to. Which is done by strcmp() and this is the right way to compare the strings.

    For example :

    #include 
    
    int main(void) {
    char *a = "test";
    char *b = "test";
    
    printf("%p\n %p",(void *)a,(void *)b);
        return 0;
    }
    

    The output is

    0x8048540 
    0x8048540
    

    So both the pointers a and b are pointing to the same memory location a==b Note that here what we compare is not the actual characters in the string but just the pointers.

    I ran the same code on another machine and the locations in which this string was stored was different.

    0x4005f8
    0x4005fd
    

    So now even though the strings might be same you see a != b. Hence use strcmp() to compare strings.

提交回复
热议问题