引用与指针及数组指针与指针数组的区别实践

实践出真知,看代码(注释记录)最好理解

#include <iostream>
#include <stdio.h>
using namespace std;

// 引用是变量的别名,指针指向变量存放变量的地址
void test0(void){
	int b = 20;
	int* x = &b;//此处&是取地址符
	int&c = b;  //此处&为象征意义,表示c也是引用
	int d = 88;
	c = d;

	cout << "test0: b: " << b << endl;
	cout << "test0: c: " << c << endl;
	cout << "test0: &c: " << &c << endl;
	cout << "test0: x: " << x << endl;
	cout << "test0: *&c: " << *&c << endl;
}

// 指针数组实际是数组,每个元素存放的是指针
void test1(void) {
	int x = 600;
	int y = 800;
	int *p[2];                 //定义一个指针数组
	p[0] = &x;
	p[1] = &y;
	printf("test1:%p\n",p[0]); //x的地址
	printf("test1:%p\n",&x);   //x的地址
	printf("test1:%d\n",*p[0]);//x的值
}

// 数组指针是指向数组的指针,存放的是数组的地址,也是数组首元素的地址
void test2(void) {
	int arrP[6] = {0,1,2,3,4,5}; //定义一个数组并赋值
	int (*p)[6] = &arrP;         //定义一个数组指针并为其赋值,可试int(*p)[5]=&arrP:cannot convert ‘int (*)[6]’ to ‘int (*)[5]’ in initialization
	printf("test2:%p\n",arrP);   //数组名为数组首元素的地址 与 &arrP[0] 等价
	printf("test2:%p\n",p);      //p为arrP的地址 及 &arrP,注意:虽然arrP与&arrP值相同,单代表的意思却不一样,类型却不同。arrP代表首元素的地址,&arrP代表数组的地址。
    printf("test2:%p\n",*p);     //*p代表arrP,所以这个表示arrP首元素的地址
    printf("test2:%d\n",**p);    //既然*p代表首元素的地址,**p为求这个地址上的值
    printf("test2:%d\n",(*p)[2]);//*p为arrP,所以(*p)[2]就是arrP[2]的值
    printf("test2:%d\n",*p[3]);  // 输出的正负整数是何意思          	
}


int main(){
	
	test0();
	
	test1();
	test2();
	
    return 0;
}

相应输出:

test0: b: 88

test0: c: 88

test0: &c: 0x7ffc89c04f08

test0: x: 0x7ffc89c04f08

test0: *&c: 88

test1:0x7ffc89c04f2c

test1:0x7ffc89c04f2c

test1:600

test2:0x7ffc89c04f10

test2:0x7ffc89c04f10

test2:0x7ffc89c04f10

test2:0

test2:2

test2:-1983885272  (每次运行都会变化)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值