簡體   English   中英

使用strcmp比較字符數組和字符指針

[英]comparing character array and character pointer using strcmp

int main(void) {
    char s[] = "ab";
    char *s1 = "ab";

    if(strcmp(s, s1))
        printf("%d", 24);
    else
        printf("%d", 23);

    return EXIT_SUCCESS;
}

為什么給出23個答案?

這是因為如果字符串相等,則strcmp返回0 0在C中被視為false

strcmp(string1, string2)

返回值

if Return value < 0 then it indicates string1 is less than string2

if Return value > 0 then it indicates string2 is less than string1

if Return value = 0 then it indicates string1 is equal to string2  

如果給定的字符串相等,則strcmp返回0,在這種情況下。 0轉換為false ,因此執行else塊,打印23

成功的strcmp返回0 因此, if失敗。

if語句更改為

if(strcmp(s , s1) == 0)

如果兩個字符串比較相等,則strcmp返回0。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM