指针与引用

取地址

#include <iostream>
using namespace std;

char a, b;
string aa;

int main(){
	char c, d;
	cout << (void*)&c << endl;
	cout << (void*)&d << endl;
	
	cout << (void*)&a << endl;
	cout << (void*)&b << endl;
	cout << &aa << endl;
	return 0;
}

image-20220418230529274
操作系统中,分为堆、栈来存储变量。局部变量存在栈中,全局变量存在堆中。32位地址可表征4GB空间。
在这里插入图片描述
因此局部变量根据定义顺序,其地址递减;
全局变量根据定义顺序,其地址递增,且地址小于局部变量。

指针

#include <iostream>
using namespace std;

char a, b;

int main(){
	int a = 10;
	int* p = &a; // p为地址

	// 可读取,并修改 类似通过数组下标修改元素值 
	cout << *p << endl; 
	*p = 12;
	
	cout << *p << endl;
	cout << a << endl; // 同样改变
	
	return 0;
}

输出:

10
12
12
数组与指针
#include <iostream>
using namespace std;


int main(){
	char c;
	int a[5] = {1, 2, 3, 4, 5};
	cout << (void*)&c << endl;
	cout << a << endl; // 数组地址
	for(int i = 0; i < 5; i ++ ){
		cout << (void*)&a[i] << endl;
	}
	
	
	return 0;
}

image-20220419003241437
注:scanf("%d", a + 1);可用于输入某个数,该表达式为对a[1]赋值为输入

指针运算

指针p+1,不是简单的地址加1,而是需要看变量类型。

#include <iostream>
using namespace std;


int main(){
	char c;
	int a[5] = {1, 2, 3, 4, 5};
	
	int *p = a;
	cout << p << endl;
	cout << (p + 1) << endl;
	
	
	return 0;
}

image-20220419003854444
指针支持同类型的加减运算:同样地,看输出相差几个该变量类型

#include <iostream>
using namespace std;


int main(){
	char c;
	int a[5] = {1, 2, 3, 4, 5};
	
	int *p = &a[0];
	int *q = &a[2];
	cout << q - p << endl;
	
	
	return 0;
}

image-20220419004614944

引用

#include <iostream>
using namespace std;


int main(){
	int a = 10;
	
//	int* p = &a;
	int& p = a; // 引用相当于别名 
	p += 5;
	cout << p << endl; 
	cout << a << endl;
	
	return 0;
}

image-20220419010711562

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值