指针

本文详细介绍了C++中的指针概念及其基本操作,包括指针的定义、使用new和delete分配与释放内存的方法,并展示了如何通过智能指针对象避免内存泄漏。此外,还探讨了使用指针进行数组和结构体的动态创建。

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

int a = 12;
int *p;
p = &a;

注意:p表示指针地址,*p是该地址内所存储的值。
当定义一个指针时, 计算机将只分配用来存储地址的内存,但不会分配用来存储指针所指向数据的内存。比如,以下代码就是错误的。

long *pl;
*pl = 123456;//place a value in never-never land, to which the pointer pl doesn't point

为此,可通过new来分配数据内存。

long *pl = new long;

但为了防止内存泄漏,用new定义的内存,都需要用delete来删除。在新版C++11中,可使用智能指针来防止内存泄漏,其将自动为我们执行删除new定义的内存。

delete pl;

再如

int *pArray = new int[10];
delete [] pArray;

对指针可以进行算术运算, 但对两个指针做加法等运算没有任何意义。

double *pd = new double[10];
pd = pd + 1; //now pd point to the second element of the array
使用指针创建动态结构
struct s {
	char charr[20];
	float a;
	double b;
};

int main() {
	s *ps = new s; //allot memory for structure s
				   //4 methods for accessing the elements of the structure
	cin.get(ps->charr, 20);
	cin >> (*ps).a; //*ps here means the structure instance
	cin >> ps->b;
	cin >>ps->charr[5];
	delete ps;
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值