可能重复:
如何在C中编译字符串文字?
我在下面写了一些小代码.在这段代码中,我认为将比较第一个和第二个"hello"字符串的地址.我很困惑.首先,我认为两个字符串都将存储在只读存储器中,因此会有不同的地址.但执行后打印出"相等".
当我看到objdump时,我无法看到字符串你好.我知道我没有采用变量来存储它们,但是"hello"存储在哪里.
它会存储在STACK上吗?还是会存储在代码段?
#include<stdio.h>
int main()
{
if ("hello" == "hello")
printf("\n equal ");
else
printf("\n not equal");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我改变if条件时 if ("hello" == "hell1"),"不等于"被打印出来.同样,字符串的存储位置和方式如何.它会存储在STACK上吗?还是会存储在代码段?
如果有人在这里给我精心解答,我真的很感激.谢谢
在您的特定示例中,“hello”字符串甚至不是代码的一部分。编译器足够聪明,可以检测到代码将永远永远打印“相等”,因此将它们完全删除。
但是,如果您的代码如下所示:
#include<stdio.h>
int main()
{
const char *h1 = "hello";
const char *h2 = "hello";
if (h1 == h2)
printf("\n equal ");
else
printf("\n not equal");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
然而,尽管实际上会完成比较(在没有额外优化的情况下编译时),您仍然会得到“相等”。这是一种优化 - 编译器检测到您有两个相同的硬编码字符串,并将它们合并到生成的二进制文件中。
然而,如果您的代码如下所示,编译器将无法(默认情况下)猜测它们是相同的,并且您将看到“不等于”消息:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char *h1 = malloc(sizeof(char) * 10);
char *h2 = malloc(sizeof(char) * 10);
strcpy(h1, "hello");
strcpy(h2, "hello");
if (h1 == h2)
printf("\n equal ");
else
printf("\n not equal");
free(h1);
free(h2);
return 0;
}
Run Code Online (Sandbox Code Playgroud)