const类型
- const修饰指针
- const修饰常量
- const修饰指针和常量
#includeint main(){ int a = 1; int b = 2; //1. const修饰指针 ----> 常量指针 const int *p = &a; // *p = 3; 报错,不能修改指针的值,只能修改它的指向 p = &b; printf("p指向的值为 %dn", *p); //2. const修饰指针 ----> 指针常量 int *const q = &a; // q = &b; 报错,只能修改指针的值,不能去修改它的指向 *q = b; printf("q指向的值为 %dn", *q); //3. const修饰指针和常量 const int *const r = 3; }
应用场景
#include#include struct Student{ char name[100]; int age; int score; }; void printStu(const struct Student *s){ printf("姓名: %s 年龄: %d 分数: %dn",s.name, s.age, s.score); } int main(){ struct Student s = {"Garrix", 27, 100}; // printStu(s); 一般用指针传递,这样系统开销会小很多,因为每次值传递,系统就会复制一份结构体 printStu(&s); }



