和实现有关的相同字符串存储方式检验的思考及c-string字符串

本文通过C++代码示例探讨了字符串字面量在内存中的存储及比较方式,揭示了即使两个相同的字符串字面量在内存中也可能位于不同的地址的事实,并提供了一种使用void*类型来正确比较字符串地址的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*Copyright (c) 2007,九天雁翎

* All rights reserved.

* 和实现有关的相同字符串存储方式检验的思考

* 完成日期:2007年7月7日*/

#include "stdafx.h"

#include <iostream>

using namespace std;

int main()

{

char *p1 = "Hello the world!";

char *p2 = "Hello the world!";

if(p1 == p2)

{

//ok,We could know it is the same as Bjarne Stroustrup said in VC++2005

cout << "The same."<<endl;

}

else

{

cout << "Not the same."<<endl;

}

//But look at this

cout << &p1 <<'/t' <<&p2 <<endl;

//the adress output is not the same!

//Do you want to output it use p1 and p2?

//Let try;

cout << p1 <<'/t' << p2 <<endl;

//We can only get the string.

//Let reaffirm it

if(&p1 == &p2)

{

cout<<"The same." <<endl;

}

else

{

cout<<"Not the same." <<endl;

}

return 0;

}

&p其实得到的是指针的地址,而不是c-string “Hello word!”的地址,而cout又为char* 重载了一个不同与一般指针的输出方式,所以你要输出”Hello world!”,可以通过static_cast<void*>方式,强制转换到void*指针,这样cout就可以输出想要的结果,结果自然和Bjarne Stroustrup说的一样,微软也没有错。

如下:

/*Copyright (c) 2007,九天雁翎

* All rights reserved.

* 和实现有关的相同字符串存储方式检验的思考

* 完成日期:2007年7月7日*/

#include "stdafx.h"

#include "myself.h"

#include <iostream>

using namespace std;

int main()

{

char *p1 = "Hello the world!";

char *p2 = "Hello the world!";

if(p1 == p2)

{

cout << "The same."<<endl;

}

else

{

cout << "Not the same."<<endl;

}

//Yes,it is.

cout << static_cast<void*>(p1) <<'/t' <<static_cast<void*>(p2) <<endl;

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值