what is the difference between “some” == “some\0” and strcmp(“some”,“some\0”) in c++?

懵懂的女人 提交于 2019-12-11 06:48:50

问题


what is the difference between "some" == "some\0" and strcmp("some","some\0") in c++?

Why if("some" == "some\0") returns false and if(!strcmp("some","some\0")) returns true ?


回答1:


See the following diagram. It shows two strings in memory, their content is in the box, beside the box you'll see the address of each one.

When you're doing if("some" == "some\0") you are comparing the addresses. It is translated into if (0xdeadbeef == 0x0badcafe) which is obviously false.

When you use strcmp, you compare the content of each box until you reach \0 in each of them. That's why the second test returns true.

If you change the first test to if("some" == "some") then a compiler may potentially see that they are the same strings and will store them only once. Which means that your test will transform into if (0x0badcafe == 0x0badcafe) which is obviously true.




回答2:


"some" == "some\0" 

compares the string literals by their addresses. These literals are stored in different memory locations. So always false.

!strcmp("some","some\0")

compares the contents of strings. Thus in that context "some\0" is same as "some". So true.

Edit: From your comments you ask that why "some" == "some" is true. That's because mostly compiler are smart enough to reuse the string literal(when they are stored in read only region). That's why it returns true.

P.S. In below case "some" is not stored in read-only:

char a[] = "some";



回答3:


The type of "some" is const char*, so when you compare "some"=="some\0" you are comparing two const char* pointers. Since they may not point to same memory location the comparison would usually fail. In the second case, you are using strcmp which compares the strings by going through individual characters in the string.



来源:https://stackoverflow.com/questions/6715247/what-is-the-difference-between-some-some-0-and-strcmpsome-some-0-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!