《第五章-心法进阶》 C++修炼生涯笔记(基础篇)指针与结构体⭐⭐⭐⭐⭐
🌟 C++指针与结构体超全指南 | 编程萌新必看!附代码运行效果💻
文末有总结表格+学习心得❤️ 建议收藏!
🔍 一、指针篇:内存操作的魔法棒✨
1️⃣ 指针定义与使用
指针就是内存地址的"导航仪"!帮你精准定位数据位置📍
#include <iostream>
using namespace std;int main() {int num = 42; // 普通变量int *p = # // p指向num的家地址🏠cout << "num的值: " << num << endl; // 42cout << "p指向的值: " << *p << endl; // 42*p = 100; // 通过指针改值cout << "修改后num: " << num << endl; // 100return 0;
}
运行结果👇
num的值: 42
p指向的值: 42
修改后num: 100
2️⃣ 指针内存空间
所有指针都是"均码"!32位穿4码👟(4字节),64位穿8码👢(8字节)
cout << "int*尺寸: " << sizeof(int*) << endl; // 4或8
cout << "double*尺寸: " << sizeof(double*) << endl; // 相同!
运行结果👇
int*尺寸: 8 // 64位系统
double*尺寸: 8
3️⃣ 空指针 vs 野指针
⚠️ 安全操作指南:
类型 | 特点 | 正确姿势 |
---|---|---|
空指针 | 安全无害的小透明🫥 | int *p = nullptr; |
野指针 | 随时爆炸的炸弹💣 | 初始化!初始化!初始化! |
int *safePtr = nullptr; // ✅ 安全空指针
// *safePtr = 10; // ❌ 禁止操作空指针!if(safePtr != nullptr) {cout << *safePtr; // 安全操作
}
4️⃣ const修饰指针
三种保护模式任你选🔒:
int a = 10, b = 20;const int *p1 = &a; // 🛡️ 保护数据(不能改值)
// *p1 = 30; // 禁止!int * const p2 = &a; // 🔐 保护指针(不能换地址)
// p2 = &b; // 禁止!const int * const p3 = &a; // 🚫 双重保护(都不能动)
// *p3=40; p3=&b; // 全禁止!
5️⃣ 指针+数组=最佳CP
指针让数组操作飞起来✈️
int arr[5] = {1,2,3,4,5};
int *p = arr; // p指向数组首地址// 三种访问方式对比
cout << "下标访问: " << arr[2] << endl; // 3
cout << "指针偏移: " << *(p+2) << endl; // 3
cout << "数组名偏移: " << *(arr+2) << endl; // 3
运行结果👇
下标访问: 3
指针偏移: 3
数组名偏移: 3
6️⃣ 指针函数参数
告别值拷贝!直改原始数据🚀
void doubleValue(int *ptr) {*ptr *= 2; // 直捣黄龙
}int main() {int num = 5;doubleValue(&num);cout << "翻倍后: " << num; // 10
}
运行结果👇
翻倍后: 10
7️⃣ 综合案例:指针操作数组
实现数组排序+查找🔍
#include <iostream>
using namespace std;// 指针版冒泡排序
void bubbleSort(int *arr, int size) {for(int i=0; i<size-1; i++) {for(int *p=arr; p<arr+size-1-i; p++) {if(*p > *(p+1)) {swap(*p, *(p+1)); // 交换相邻元素}}}
}int main() {int nums[] = {5,3,8,1,4};int len = sizeof(nums)/sizeof(nums[0]);cout << "排序前: ";for(int i=0; i<len; i++) cout << nums[i] << " ";bubbleSort(nums, len);cout << "\n排序后: ";for(int i=0; i<len; i++) cout << nums[i] << " ";
}
运行结果👇
排序前: 5 3 8 1 4
排序后: 1 3 4 5 8
🧩 二、结构体篇:自定义数据容器📦
1️⃣ 结构体定义与使用
打造专属数据模板🎨
struct Student {string name;int age;float score;
};int main() {// 创建结构体变量Student s1;s1.name = "小明";s1.age = 18;s1.score = 92.5f;// 初始化写法Student s2 = {"小红", 17, 88.5};cout << s1.name << "的成绩:" << s1.score << endl;
}
运行结果👇
小明的成绩:92.5
2️⃣ 结构体数组
批量管理神器📚
struct Book {string title;string author;float price;
};int main() {Book library[3] = {{"C++ Primer", "Stanley", 99.9},{"Effective C++", "Scott", 89.5},{"Clean Code", "Robert", 79.8}};cout << "第二本书: " << library[1].title; // Effective C++
}
运行结果👇
第二本书: Effective C++
3️⃣ 结构体指针
高效访问技巧⚡
Student s = {"小刚", 20, 95.0};
Student *ptr = &s;cout << ptr->name; // 小刚(等价于(*ptr).name)
ptr->score = 98.5; // 修改成绩
4️⃣ 结构体嵌套
俄罗斯套娃式设计🎭
struct Address {string city;string street;int number;
};struct User {string name;Address addr; // 嵌套结构体
};int main() {User u = {"小美", {"上海", "南京路", 1024}};cout << u.name << "住在" << u.addr.city;
}
运行结果👇
小美住在上海
5️⃣ 结构体函数参数
三种传递方式对比🆚
方式 | 语法 | 特点 |
---|---|---|
值传递 | void func(Student s) | 创建副本,效率低 |
指针传递 | void func(Student *s) | 直接操作原数据✅ |
引用传递 | void func(Student &s) | 最推荐方式💯 |
// 引用传递修改结构体
void raiseScore(Student &s, float bonus) {s.score += bonus;
}Student stu = {"小林", 19, 80};
raiseScore(stu, 5.5);
cout << "新成绩: " << stu.score; // 85.5
6️⃣ 结构体const保护
防手抖神器🤚
struct Account {string id;float balance;// const成员函数:禁止修改数据void show() const {// balance = 0; // ❌ 禁止修改!cout << "账户:" << id << " 余额:" << balance;}
};int main() {const Account acc = {"666", 5000};// acc.balance = 0; // ❌ 禁止修改常量结构体acc.show(); // ✅ 允许只读操作
}
🚀 三、综合应用:员工管理系统
#include <iostream>
using namespace std;struct Employee {int id;string name;double salary;
};// 打印员工信息
void printEmp(const Employee *emp) {cout << "ID:" << emp->id << " 姓名:" << emp->name << " 薪水:" << emp->salary << endl;
}// 加薪函数
void raiseSalary(Employee *emp, double percent) {emp->salary *= (1 + percent/100);
}int main() {Employee e1 = {101, "张三", 8000};cout << "👉 加薪前:" << endl;printEmp(&e1);raiseSalary(&e1, 15); // 加薪15%cout << "\n🎉 加薪后:" << endl;printEmp(&e1);return 0;
}
运行结果👇
👉 加薪前:
ID:101 姓名:张三 薪水:8000🎉 加薪后:
ID:101 姓名:张三 薪水:9200
💎 核心要点总结表
知识点 | 关键语法 | 使用技巧 |
---|---|---|
指针定义 | int *p = &变量; | 用前初始化为nullptr |
空指针 | nullptr | 操作前检查是否为空 |
const指针 | const int *p | 按需选择保护模式 |
指针+数组 | int *p = arr; | p+1指向下一个元素 |
结构体定义 | struct {成员...}; | 相关数据打包管理 |
结构体指针 | Student *ptr = &s; | 访问成员用ptr->name |
结构体嵌套 | 结构体包含结构体成员 | 实现数据分层管理 |
const结构体 | void func() const {...} | 防止意外修改成员数据 |
✨学习心得:
1️⃣ 指针像激光笔🔦 - 精准指向内存位置,但别晃到危险区域!
2️⃣ 结构体像收纳盒🗃️ - 把杂乱数据整理得井井有条
3️⃣ const是护身符🧿 - 重要数据加上保护防误改
4️⃣ 多写注释📝 - 复杂指针操作一定要标注清楚
5️⃣ 画内存图📊 - 遇到困惑就画图辅助理解