指针常量,常量指针,指针修饰的常量,常量修饰的指针区别

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;
}
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值