C语言 - const

C语言 - const 首页 / C语言入门教程 / C语言 - const

C中的常量指针无法更改其指向的变量的地址,即该地址将保持不变。因此,可以说,如果常量指针指向某个变量,则它不能指向任何其他变量。

常量指针语法

<type of pointer> *const <name of pointer>;

常量指针的声明如下:

int *const ptr;

让我们通过示例了解常量指针。

#include <stdio.h>
int main()
{
    int a=1;
    int b=2;
    int *const ptr;
    ptr=&a;
    ptr=&b;
    printf("Value of ptr is :%d",*ptr);
    return 0;
}

在上面的代码中:

  • 我们声明两个变量,即a和b分别具有值1和2。
  • 我们声明一个常量指针。
  • 首先,我们将变量" a"的地址分配给指针" ptr"。
  • 然后,我们将变量'b'的地址分配给指针'ptr'。
  • 最后,我们尝试打印'ptr'指向的变量的值。

输出

const Pointer in C

在上面的输出中,我们可以看到上面的代码产生错误“assignment of read-only variable 'ptr'"。这意味着不能更改"ptr"持有的变量"ptr"的值。在上面的代码中,我们将'ptr'的值从&a更改为&b,这对于常量指针是不可能的。因此,可以说指向某个变量的常量指针不能指向另一个变量。

指向常量的指针

指向常量的指针是一种指针,通过该指针不能更改指针所指向的变量的值。这些指针的地址可以更改,但是指针指向的变量的值不能更改。

语法 of 指向常量的指针

const <type of pointer>* <name of pointer>

下面给出了指向常量的指针的声明:

const int* ptr;

通过示例让我们理解。

  • 首先,我们在更改指针值的地方编写代码
#include <stdio.h>
int main()
{
    int a=100;
    int b=200;
    const int* ptr;
    ptr=&a;
    ptr=&b;
    printf("Value of ptr is :%u",ptr);
    return 0;
}

在上面的代码中:

  • 我们声明两个变量,即a和b分别具有值100和200。
  • 我们声明一个指向常量的指针。
  • 首先,我们将变量" a"的地址分配给指针" ptr"。
  • 然后,我们将变量'b'的地址分配给指针'ptr'。
  • 最后,我们尝试打印'ptr'的值。

输出

const Pointer in C

上面的代码成功运行,并且在输出中显示了'ptr'的值。

  • 现在,我们编写代码来更改指针所指向的变量的值。
#include <stdio.h>
int main()
{
    int a=100;
    int b=200;
    const int* ptr;
    ptr=&b;
    *ptr=300;
    printf("Value of ptr is :%d",*ptr);
    return 0;
}

在上面的代码中:

  • 我们声明两个变量,即分别为100和200的'a'和'b'。
  • 我们声明一个指向常量的指针。
  • 我们将变量" b"的地址分配给指针" ptr"。
  • 然后,我们尝试通过指针'ptr'修改变量'b'的值。
  • 最后,我们尝试打印指针'ptr'指向的变量的值。

输出

const Pointer in C

上面的代码显示错误"assignment of read-only location * ptr'"。此错误意味着我们无法更改指针指向的变量的值。

指向常量的常量指针

指向常量的常量指针是一个指针,它是上述两个指针的组合。它既不能更改其指向的变量的地址,也不能更改该地址处的值。

const <type of pointer>* const <name of the pointer>;

常量的声明如下:

const int* const ptr;

通过示例让我们理解。

#include <stdio.h>
int main()
{
    int a=10;
    int b=90;
    const int* const ptr=&a;
   *ptr=12;
    ptr=&b;
    printf("Value of ptr is :%d",*ptr);
    return 0;
} 

在上面的代码中:

  • 我们声明两个变量,分别为'a'和'b',其值分别为10和90。
  • 我们声明一个指向常量的常量指针,然后分配'a'的地址。
  • 我们尝试通过指针" ptr"更改变量" a"的值。
  • 然后我们尝试将变量'b'的地址分配给指针'ptr'。
  • 最后,我们打印变量的值,该值由指针'ptr'指向。

输出

const Pointer in C

上面的代码显示错误"assignment  of read-only location '* ptr'的分配"和"assignment  of read-only variable  'ptr'的分配"。因此,我们得出的结论是,指向常量的常量指针不能更改该指针指向的地址或值。

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

趣谈网络协议 -〔刘超〕

数据分析实战45讲 -〔陈旸〕

Service Mesh实战 -〔马若飞〕

视觉笔记入门课 -〔高伟〕

动态规划面试宝典 -〔卢誉声〕

深入剖析Java新特性 -〔范学雷〕

攻克视频技术 -〔李江〕

React Native 新架构实战课 -〔蒋宏伟〕

LangChain 实战课 -〔黄佳〕

好记忆不如烂笔头。留下您的足迹吧 :)