迷途指针的问题?

xiaoshahui1 2003-10-19 05:03:21
以下有一程序:
1 typedef unsigned short int USHORT;
2 #include <iostream>
3
4 int main
5 {
6 USHORT *pInt=new USHORT;
7 *pInt=10;
8 std::cout<<"*pInt: "<<*pInt<<std::endl;
9 delete pInt;
10
11 long *pLong=new long;
12 *pLong=90000;
13 std::cout<<"*pLong: "<<*pLong<<std::endl;
14
15 *pInt=20;
16
17 std::cout<<"*pInt: "<<*pInt<<std::endl;
18 std::cout<<"*pLong: "<<*pLong<<std::endl;
19 delete pLong;
20 return 0;
21 }
输出:
*pInt: 10
*pLOng: 90000
*pInt: 20
*pLong: 65556
请问大家在第9行释放了pInt所指向的内存空间,但为什么在第11行将pInt原来内存地址赋给了指针pLong,这难道是巧合吗?那么这时候是不是pInt就指向了为long所分配的内存地址?为什么呢?他不是已经被释放了吗?按理说18行应该输出为20,但怎么变成了65556?
...全文
157 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
xiaoshahui1 2003-10-20
  • 打赏
  • 举报
回复
谢谢大家的回复!!!
soltek 2003-10-19
  • 打赏
  • 举报
回复
你改动的这个程序好像有点问题吧?
可以执行一下
LeeDee818 2003-10-19
  • 打赏
  • 举报
回复
你可以试试这个程序:

typedef unsigned short int USHORT;
#include <iostream>

int main ( void )
{
USHORT *pInt=new USHORT;
*pInt=10;
std::cout<<pInt<< endl; //这里
std::cout<<"*pInt: "<<*pInt<<std::endl;
delete pInt;

long *pLong=new long;
std::cout<<pInt<< endl; // 这里
*pLong=90000;
std::cout<<"*pLong: "<<*pLong<<std::endl;

*pInt=20;

std::cout<<"*pInt: "<<*pInt<<std::endl;
std::cout<<"*pLong: "<<*pLong<<std::endl;
delete pLong;
return 0;
}

只不过在你的程序中加了两行,它们分别输出两个变量的地址
你会看到地址值是一样的.

在C++中,delete一个指针仅仅把它所指向的内存区标明为可用.而不会改变指针所指向的地址值.所以,两个指针指向了同一个地址.

而,在计算机中,数据存储是低位在前:比如你的
*pLong=90000;

在内存中存为:
90 5f 01 00

而后来的pInt也指向这个区域,又赋值:
*pInt=20;

使那片内存更改为:
14 00 01 00

当输出pLong时,就会输出65556(010014h)


Jinhao 2003-10-19
  • 打赏
  • 举报
回复
1,
7 *pInt=10;
8 std::cout<<"*pInt: "<<*pInt<<std::endl;
9 delete pInt; //操作系统可以再使用pInt所指的内存
10
11 long *pLong=new long; //操作系统分配内存时,就包含了pInt所指的内存

2,
第18行不会输出20的
首先*pInt是包含在*pLong中的,且只占有了2个字节(long是4个字节),所以*pInt=20,只修改了*pLong中的2个字节,还有2个字节没有被修改,所以...
kfangx 2003-10-19
  • 打赏
  • 举报
回复
是的。C语言库在new USSHORT被释放后,这些内存空间就空闲了。new long与new USSHORT所指的内存一样。

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧