const修饰指针:
int a = 10;
int b = 10;
// const修饰的是指针的内容,指针的指向可以改,指针指向的内容不可以改
const int *p1 = &a;
p1 = &b; // 正确,改变了指针的指向
*p1 = 100; // 错误,改变了指针指向的内容
// const修饰的是指针的指向,指针的指向不可以改,指针指向的内容可以改
int * const p2 = &a;
p2 = &b; // 错误,改变了指针的指向
*p2 = 100; // 正确,改变了指针指向的内容
// const既修饰指针的指向,又修饰指针指向的内容
const int * const p3 = &a;
p3 = &b; // 错误
*p3 = 100; // 错误
指针和数组:
int arr[] = {1,2,3,4,5,6,7,8,9,10};
int *p = arr; // 此时指针p指向数组arr的首地址(即arr[0]的地址)
for (int i = 0; i < 10; i++) {
cout << *p << endl;
p++; // 让指针指向的地址往后挪一位
}
在函数中使用指针(值传递和地址传递的区别):
//值传递,不改变实参
void swap1(int a, int b) {
int temp = a;
a = b;
b = temp;
}
//地址传递,改变实参
void swap2(int *p1, int *p2) {
int temp = *p1;
*p1 = *p2;
*p2 = temp;
}
int main() {
int a = 10;
int b = 20;
swap1(a, b); // 值传递,不改变实参
swap2(&a, &b); // 地址传递,改变实参
}
指针配合数组和函数:
// 冒泡排序函数
void bubbleSort(int *arr, int len) {
for (int i=0; i < len-1; i++) {
for (int j = 0; j < len-1-i; j++) {
if (arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
int main() {
int arr[10] = {1,2,3,4,5,6,7,8,9,10};
int len = sizeof(arr) / sizeof(arr[0]); // 数组长度
bubbleSort(arr, len);
system("pause");
return 0;
}
结构体的定义:
#include<string>
struct Student {
string name;
int age;
int score;
};
int main() {
Student s1;
s1.name = "ZhangSan";
s1.age = 18;
s1.score = 100;
Student s2 = {"LiSi", 19, 80};
}
结构体数组:
#include<string>
struct Student {
string name;
int age;
int score;
};
int main() {
Student stuArray[3] = {
{"aaa", 18, 100},
{"bbb", 20, 99},
{"ccc", 30, 60}
};
//给结构体中的元素赋值
stuArray[2].name = "ddd";
stuArray[2].age = 50;
}
结构体指针:
#include<string>
struct Student {
string name;
int age;
int score;
};
int main() {
Student s = {"aaa", 18, 100};
Student *p = &s;
//通过指针访问结构体变量中的数据
p->name = "bbb";
p->age = 28;
}
结构体嵌套结构体:
#include<string>
struct student {
string name;
int age;
int score;
};
struct teacher {
int id;
string name;
int age;
struct student stu;
};
int main() {
teacher t;
t.id = 1000;
t.name = "bbb";
t.age = 50;
t.stu.name = "aaa";
t.stu.age = 20;
t.stu.score = 60;
}
结构体做函数参数:
两种传递方式:
- 值传递;
- 地址传递;
#include<string>
struct student {
string name;
int age;
int score;
};
//值传递
void printStudent1(student stu) {
stu.age = 20; // 不会改变实参的值
}
//地址传递
void printStudent2(student *stu) {
stu->age = 20; // 会改变实参的值
}
int main() {
student stu = {"aaa", 18, 100};
printStudent1(stu);
cout << stu.age << endl;
printStudent2(&stu);
cout << stu.age << endl;
return 0;
}
结构体中const的使用:
void printStudent2(const student *stu) { // 加入const,防止对内容进行修改
stu->age = 20; // 错误,不允许对const修饰的内容进行修改
}
int main() {
student stu = {"aaa", 18, 100};
printStudent2(&stu);
cout << stu.age << endl;
return 0;
}