1.指针常量 (Pointer to Constant):
int x = 10;
int y = 20;
const int *ptr; // 指针常量,指向常量整数
ptr = &x; // 合法,ptr指向x
// *ptr = 5; // 非法,不能通过ptr修改所指向的值
x = 15; // 合法,通过x修改值
在这个例子中,ptr是一个指向常量整数的指针。这意味着你可以改变ptr指向的变量的地址,但不能通过ptr来修改所指向的值。
2.常量指针 (Constant Pointer):
int x = 10;
int y = 20;
int *const ptr = &x; // 常量指针,指针本身是常量
// ptr = &y; // 非法,不能修改指针本身的值
*ptr = 15; // 合法,可以通过ptr修改所指向的值
// ptr++; // 非法,不能改变指针本身的地址
在这个例子中,ptr是一个指向整数的常量指针。这意味着你可以通过ptr来修改所指向的值,但不能修改ptr指针本身的地址。
3.指针修饰的常量 (Pointer with Constant):
int x = 10;
int y = 20;
int const *ptr = &x; // 指针修饰的常量,指向整数的常量指针
ptr = &y; // 合法,ptr可以指向不同的常量整数
// *ptr = 25; // 非法,不能通过ptr修改所指向的值
在这个例子中,ptr是一个指向整数常量的指针。这意味着你可以改变ptr指向的变量的地址,但不能通过ptr来修改所指向的值。
4.常量修饰的指针 (Constant Pointer with Constant):
int x = 10;
int y = 20;
const int *const ptr = &x; // 常量修饰的指针,指向常量整数的常量指针
// ptr = &y; // 非法,不能修改指针本身的值
// *ptr = 30; // 非法,不能通过ptr修改所指向的值
在这个例子中,ptr是一个指向常量整数的常量指针。这意味着既不能改变ptr指针本身的地址,也不能通过ptr来修改所指向的值。
下面是指针修饰的常量(Pointer with Constant)、常量修饰的指针(Constant Pointer)、指针常量(Pointer to Constant)和常量指针(Constant Pointer)的具体代码演示:
#include <stdio.h>
int main() {
int x = 10;
int y = 20;
// 指针常量,指向常量整数
const int *ptr_to_const;
ptr_to_const = &x; // 合法,ptr_to_const指向x
// *ptr_to_const = 5; // 非法,不能通过ptr_to_const修改所指向的值
// 常量指针,指针本身是常量
int *const const_ptr = &x;
// const_ptr = &y; // 非法,不能修改const_ptr指针本身的值
*const_ptr = 15; // 合法,可以通过const_ptr修改所指向的值
// 指针修饰的常量,指向整数的常量指针
int const *ptr_with_const;
ptr_with_const = &x; // 合法,ptr_with_const指向x
// *ptr_with_const = 25; // 非法,不能通过ptr_with_const修改所指向的值
// 常量修饰的指针,指向常量整数的常量指针
const int *const const_ptr_with_const = &x;
// const_ptr_with_const = &y; // 非法,不能修改const_ptr_with_const指针本身的值
// *const_ptr_with_const = 30; // 非法,不能通过const_ptr_with_const修改所指向的值
printf("x: %d, y: %d\n", x, y);
printf("Value pointed by ptr_to_const: %d\n", *ptr_to_const);
printf("Value pointed by const_ptr: %d\n", *const_ptr);
printf("Value pointed by ptr_with_const: %d\n", *ptr_with_const);
printf("Value pointed by const_ptr_with_const: %d\n", *const_ptr_with_const);
return 0;
}