📌  相关文章
📜  const char * p,char * const p和const char * const p之间的区别

📅  最后修改于: 2021-05-30 20:23:38             🧑  作者: Mango

先决条件:指针
当char,const,*,p都用在不同的排列中时,含义会根据放置在何处而变化,这会引起很多混乱。下一篇文章重点介绍所有这些的区别和用法。

限定符const可以应用于任何变量的声明,以指定其值不会更改。 const关键字适用于紧靠其左侧的任何内容。如果左侧没有任何内容,则适用于右侧的任何内容。

  1. const char * ptr:这是指向常量字符的指针。您不能更改ptr所指向的值,但是可以更改指针本身。 “ const char *”是指向const char的(非const)指针。
    // C program to illustrate 
    // char const *p
    #include
    #include
      
    int main()
    {
        char a ='A', b ='B';
        const char *ptr = &a;
          
        //*ptr = b; illegal statement (assignment of read-only location *ptr)
          
        // ptr can be changed
        printf( "value pointed to by ptr: %c\n", *ptr);
        ptr = &b;
        printf( "value pointed to by ptr: %c\n", *ptr);
    }
    

    输出:

    value pointed to by ptr:A
    value pointed to by ptr:B
    

    注意: const char * p和char const * p之间没有区别,因为它们都是指向const char的指针,并且’*’(asterik)的位置也相同。

  2. char * const ptr:这是指向非恒定字符的恒定指针。您不能更改指针p,但可以更改ptr指向的值。
    // C program to illustrate 
    // char* const p
    #include
    #include
      
    int main()
    {
        char a ='A', b ='B';
        char *const ptr = &a;
        printf( "Value pointed to by ptr: %c\n", *ptr);
        printf( "Address ptr is pointing to: %d\n\n", ptr);
      
        //ptr = &b; illegal statement (assignment of read-only variable ptr)
      
        // changing the value at the address ptr is pointing to
        *ptr = b; 
        printf( "Value pointed to by ptr: %c\n", *ptr);
        printf( "Address ptr is pointing to: %d\n", ptr);
    }
    

    输出:

    Value pointed to by ptr: A
    Address ptr is pointing to: -1443150762
    
    Value pointed to by ptr: B
    Address ptr is pointing to: -1443150762
    

    注意:指针总是指向相同的地址,只有该位置的值被更改。

  3. const char * const ptr:这是指向常量字符的常量指针。您既不能更改ptr所指向的值,也不能更改指针ptr。
    // C program to illustrate 
    //const char * const ptr 
    #include
    #include
      
    int main()
    {
        char a ='A', b ='B';
        const char *const ptr = &a;
          
        printf( "Value pointed to by ptr: %c\n", *ptr);
        printf( "Address ptr is pointing to: %d\n\n", ptr);
      
        // ptr = &b; illegal statement (assignment of read-only variable ptr)
        // *ptr = b; illegal statement (assignment of read-only location *ptr)
      
    }
    

    输出:

    Value pointed to by ptr: A
    Address ptr is pointing to: -255095482
    

    注意:char const * const ptrconst char * const ptr相同

const关键字测验

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。