C字符串比较 - 等于true [英] C String Comparison - equates to true

查看:140
本文介绍了C字符串比较 - 等于true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许是一个奇怪的问题。

Perhaps an odd question..

我目前正在努力理解为什么以下等于真,即Hello World被打印到控制台?我一直认为C中的字符串比较必须使用 strcmp 或类似的。

I'm currently struggling to understand why the following equates to true i.e. "Hello World" is printed to the console? I've always thought that string comparison in C had to be done using strcmp or similar.

char *a = "Hello";
char *b = "Hello";

if(a == b)
{
    printf("Hello World\n");
}

我还认为如果地址相同,这只会等于true?这是事实,他们是文字?

I also thought that this would only equate to true if the addresses were equivalent? Is it the fact that they're literals?

PS。是的,这与任务几乎没有关系,但我只是想出了上面从我的头顶。

推荐答案

您直接放入代码的相同文字

Identical literals that you put directly into the code will actually be pointed at the same memory location for optimization purposes.

编译器在这种情况下在固定内存中放置一次Hello,然后指向

The compiler in this case puts down "Hello" once in fixed memory, then points a and b at that memory.

有关详细信息,请参阅我建议你编译这个程序(首先添加一串字符串文字),然后使用 gdb 或valgrind或任何其他内存检查器,并手动查看内存指向字符串文字 - 你会发现在标准的情况下gcc将所有的字符串字面量放在内存中并重用相同的字符串文字。

For a more detailed understanding of what's going on, I suggest you compile this program (add a bunch of string literals first), then use gdb or valgrind or any other memory inspector and manually take a look at the memory pointing to string literals -- you'll find in standard cases gcc puts all the string literals together in memory and re-uses identical string literals.

这篇关于C字符串比较 - 等于true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆