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");
}
待更新。