C语言常量指针

示例

单指针

  • 指向一个指针 int

    指针可以指向不同的整数,并且int可以通过指针更改。此代码示例将b指向,int b然后将其b值更改为100。

    int b;
    int* p;
    p = &b;    /* OK */
    *p = 100;  /* OK */
  • 指向一个指针 const int

    指针可以指向不同的整数,但int不能通过指针更改的值。

    int b;
    const int* p;
    p = &b;    /* OK */
    *p = 100;  /* Compiler Error */
  • const 指向 int

    指针只能指向1,int但int可以通过指针更改其值。

    int a, b;
    int* const p = &b; /* OK as initialisation, no assignment */
    *p = 100;  /* OK */
    p = &a;    /* Compiler Error */
  • const 指向 const int

    指针只能指向一个,int并且int不能通过指针更改。

    int a, b;
    const int* const p = &b; /* OK as initialisation, no assignment */
    p = &a;   /* Compiler Error */
    *p = 100; /* Compiler Error */

指针到指针

  • 指向一个指针的指针 int

    这段代码将的地址分配p1给double指针p(然后指向)int* p1(指向int)。

    然后更改p1为指向int a。然后将a的值更改为100。

    void f1(void)
    {
     int a, b;
     int *p1;
     int **p;
     p1 = &b; /* OK */
     p = &p1; /* OK */
     *p = &a; /* OK */
     **p = 100; /* OK */
    }
  • 指向a的指针 const int

     void f2(void)
    {
     int b;
     const int *p1;
     const int **p;
     p = &p1; /* OK */
     *p = &b; /* OK */
     **p = 100; /* error: assignment of read-only location ‘**p’ */
    }
  • 指向const一个指针的指针int

    void f3(void)
    {
     int b;
     int *p1;
     int * const *p;
     p = &p1; /* OK */
     *p = &b; /* error: assignment of read-only location ‘*p’ */
     **p = 100; /* OK */
    }
  • const 指向的指针 int

    void f4(void)
    {
     int b;
     int *p1;
     int ** const p = &p1; /* OK as initialisation, not assignment */
     p = &p1; /* error: assignment of read-only variable ‘p’ */
     *p = &b; /* OK */
     **p = 100; /* OK */
    }
  • 指向的const指针const int

    void f5(void)
    {
     int b;
     const int *p1;
     const int * const *p;
     p = &p1; /* OK */
     *p = &b; /* error: assignment of read-only location ‘*p’ */
     **p = 100; /* error: assignment of read-only location ‘**p’ */
    }
  • const 指向的指针 const int

    void f6(void)
    {
     int b;
     const int *p1;
     const int ** const p = &p1; /* OK as initialisation, not assignment */
     p = &p1; /* error: assignment of read-only variable ‘p’ */
     *p = &b; /* OK */
     **p = 100; /* error: assignment of read-only location ‘**p’ */
    }
  • const指向的const指针int

    void f7(void)
    {
     int b;
     int *p1;
     int * const * const p = &p1; /* OK as initialisation, not assignment */
     p = &p1; /* error: assignment of read-only variable ‘p’  */
     *p = &b; /* error: assignment of read-only location ‘*p’ */
     **p = 100; /* OK */
    }