两个字符串文字具有相同的指针值? [英] Two string literals have the same pointer value?

查看:113
本文介绍了两个字符串文字具有相同的指针值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用MinGW运行此程序时,输出为=

 #include< iostream> 

using namespace std;

int main()
{
char * str1 =Hello;
char * str2 =Hello;

if(str1 == str2)
cout<<=;
else
cout<<!=;


return 0;但是,在逻辑上,它应该是!=,coz这些都是指针和他们指向不同的存储器位置。当我在我的Turbo C ++中运行这个代码时,我得到了!=

解决方案

然而,它们是否指向不同的位置取决于实现。对于编译器只存储一次字符串字面值并在代码中使用它的地址,它是完全有效的。


When I run this program using MinGW, im getting output as "="

#include<iostream>

using namespace std;

int main()
{
 char *str1 = "Hello";
 char *str2 = "Hello";

 if(str1==str2)
 cout<<"=";
 else
 cout<<"!=";


 return 0;
}

However, logically, it should be !=, coz these are pointers and they are pointing to different memory locations. When I run this code in my Turbo C++, i get !=

解决方案

You are right in that they are pointers. However, whether they are pointing to different locations or not depends on the implementation. It is perfectly valid for a compiler to store a string literal just once and use its address wherever it's used in code.

这篇关于两个字符串文字具有相同的指针值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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