C 字符串与等号的比较

标签 c string c-strings

我有这个代码:

char *name = "George"

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

我认为 c 字符串不能与 == 符号进行比较,我必须使用 strcmp。由于未知原因,当我使用 gcc(版本 4.7.3)编译时,此代码有效。我认为这是错误的,因为它就像比较指针,所以我在谷歌中搜索,很多人说这是错误的,无法与 == 进行比较。那么为什么这种比较方法有效呢?

最佳答案

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

没错。

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

也对。

So why this comparing method works ?

它不“工作”。它只是似乎在工作。

发生这种情况的原因可能是编译器优化:两个字符串文字是相同的,因此编译器实际上只生成它们的一个实例,并在引用字符串文字时使用完全相同的指针/数组。

关于C 字符串与等号的比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17781855/

相关文章:

c - C 上下文中的 Valgrind 错误

c - 低位和高位 DWORD => size_t

python - 如何将正则表达式转换为列表

c - C语言输入字符串如何加下划线

c - 为什么输出会无限循环

python - Python 3.x 中整个文本文件的字符串替换?

C++ 收银机程序不使用 <string>

c - 定长空字符串中的空字符在哪里?

c++ - 如何在 C++ 中正确分配 char*?

c - 我做错了什么错误: invalid operands to binary * (have 'float *' and 'int' )|