What is the difference between char * const and const char *?

前端 未结 19 1473
执笔经年
执笔经年 2020-11-22 03:31

What\'s the difference between:

char * const 

and

const char *
19条回答
  •  無奈伤痛
    2020-11-22 03:50

    1. Constant pointer: A constant pointer can point only to a single variable of the respective data type during the entire program.we can change the value of the variable pointed by the pointer. Initialization should be done during the time of declaration itself.

    Syntax:

    datatype *const var;
    

    char *const comes under this case.

    /*program to illustrate the behaviour of constant pointer */
    
    #include
    int main(){
      int a=10;
      int *const ptr=&a;
      *ptr=100;/* we can change the value of object but we cannot point it to another variable.suppose another variable int b=20; and ptr=&b; gives you error*/
      printf("%d",*ptr);
      return 0;
    }
    
    1. Pointer to a const value: In this a pointer can point any number of variables of the respective type but we cannot change the value of the object pointed by the pointer at that specific time.

    Syntax:

    const datatype *varor datatype const *var

    const char* comes under this case.

    /* program to illustrate the behavior of pointer to a constant*/
    
       #include
       int main(){
           int a=10,b=20;
           int const *ptr=&a;
           printf("%d\n",*ptr);
           /*  *ptr=100 is not possible i.e we cannot change the value of the object pointed by the pointer*/
           ptr=&b;
           printf("%d",*ptr);
           /*we can point it to another object*/
           return 0;
        }
    

提交回复
热议问题