C++学习之路(二)

#include<iostream>

int main()
{
	using namespace std;
	unsigned short int myAge = 5, yourAge = 10;
	unsigned short int * pAge = &myAge;

	cout << "myAge:\t" << myAge
		<< "\t\tyourAge:\t" << yourAge << endl;

	cout << "&myAge:\t" << &myAge
		<< "\t&yourAge:\t" << &yourAge << endl;

	cout << "pAge:\t" << pAge << endl;
	cout << "pAge:\t" << *pAge << endl;

	cout << "\nReassigning:pAge=&yourAge..." << endl << endl;
	pAge = &yourAge;

	cout << "myAge:\t" << myAge <<
		"\t\tyourAge:\t" << yourAge << endl;

	cout << "&myAge:\t" << &myAge
		<< "\t&yourAge:\t" << &yourAge << endl;

	cout << "pAge:\t" << pAge << endl;
	cout << "*pAge:\t" << *pAge << endl;

	cout << "\n&pAge:\t" << &pAge << endl;

	system("pause");

	return 0;
}

输出结果:


数组名是指向数组第一个元素的指针;

局部变量和函数参数位于堆栈中,当然,代码位于代码空间中,而全局变量位于全局名称空间中,寄存器用于内部管理工作,如记录栈顶指针和指令指针,余下的所有内存被作为自由存储区,通常称为堆;

使用关键字new来分配自由存储区中的内存,new的返回值是一个内存地址;

unsigned short int * pPointer=new unsigned short int;

#include<iostream>
int main()
{  using namespace std;
   int localVariable=5;
   int * pLocal=&localVariable;
   int * pHeap=new int;
   *pHeap=7;
   cout<<"localVariable:"<<localVariable<<endl; 
   cout<<"*pLocal:"<<*pLocal<<endl;
   cout<<"*pHeap:"<<*pHeap<<endl;
   delete pHeap;
   pHeap=new int;
   *pHeap=9;
   cout<<"*pHeap:"<<*pHeap<<endl;
   delete pHeap;
   return 0;
}

//避免迷途指针:

USHORT  * pInt=new USHORT;

* pInt=10;

delete pInt;

*pInt=20       //注意:这样做是不对的,应该将指针设置为空(0)或者 重新分配pInt=new USHORT再使用

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值