C++ 01常量指针和指针常量、数组指针和指针数组、引用和指针,结构体数组和结构体指针,常量引用

1. 常量指针、指针常量 

int main(){

	//  1,常量指针,const修饰常量,指针指向的值不可以改
	int a = 10;
	int b = 10;
	const int * p = &a;
	// *p = 20; // 错位
	// p = &b; // 正确

	// 2,指针常量,const修饰指针,指针的指向不能变
	int * const p2 = &a;  // 指针常量,*p不能改
	// *p2 = 100; // 正确
	// p2 = &b;// 错误

	// 3,const修饰指针,也修饰常量
	const int * const p3 = &a;
	// *p3 = 100; // 错误
	// p3 = &b;// 错误


	system("pause");
}

2. 数组指针和指针数组

int main(){
	
	int arr1[2] = {1, 2};
	int a1 = 1;
	int a2 = 1;


	// 1,指针数组,arr2是一个数组,数组里面存放的是int *类型的指针
	int * arr2[2];
	arr2[0] = &a1;
	arr2[1] = &a2;
	cout << "arr2[0] = " << arr2[0] << endl;
	cout << "arr2[0] 指针指向的值是: " << *arr2[0] << endl;

	// 2,数组指针,p是一个指针,指向一个数组
	int * p = arr1;
	for (int i = 0; i < 2; i++)
	{
		cout << *p << endl;
		p++;
	}

	system("pause");

}

3. 引用和指针

指针:指针就是地址

引用:引用是变量的别名,是变量的第二个名字

4. 结构体数组和结构体指针

结构体数组

#include<iostream>
#include<string>
using namespace std;

struct Student
{
	string name;
	int age;
	int score;
};

int main()
{
	// 创建数组
	struct Student stuArray[2] =
	{
		{ "张三", 18, 90 },
		{ "李四", 20, 100 },
	};

	// 结构体数组中的元素赋值
	stuArray[1].name = "赵六";
	stuArray[1].age = 80;
	stuArray[1].score = 60;

	for (int i = 0; i < 2; i++)
	{
		cout << "姓名: " << stuArray[i].name 
			<< "年龄: " << stuArray[i].age
			<< "分数: " << stuArray[i].score << endl;

	}

	system("pause");

}

结构体指针

#include<iostream>
#include<string>
using namespace std;

struct Student
{
	string name;
	int age;
	int score;
};

int main()
{
	// 1 创建结构体变量
	struct Student s = { "张三", 18, 100 };
	
	// 2 结构体指针
	struct Student * p = &s;

	// 3 通过指针访问结构体变量中的成员
	cout << "姓名: " << p->name
		<< "年龄:" << p->age
		<< "分数: " << p->score << endl;

	system("pause");

}

 

注:将函数中的形参改为指针,可以减少内存消耗(值传递是复制),但是指针可能会修改实参的值,这时可用const 修饰形参,例如形参是const struct Student *s,这样结构体s既可以不耗内存地操作属性,又可以做到不修改实参原有的值。

5. 常量引用
     常量引用 const int & val
     使用场景:操作形参时,不能改变实参,首先想到的是值传递,但是值传递增加内存消耗,
     所以改为引用传递,但引用传递可能会改变实参,
     所以使用常量引用,const修饰形参,防止误操作,改变了实参。

#include<iostream>
using namespace std;

void printValue(const int &value)
{
	cout << "value: " << value << endl;
}

int main()
{	
	int a = 100;
	printValue(a);

	system("pause");
}

 

待更新。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mr.Q

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值