char* vs const char* as a parameter

后端 未结 5 495
逝去的感伤
逝去的感伤 2021-01-30 05:10

There are many times that I get compile errors when I use char* instead of const char*. So, I am not sure the actual difference, the syntax and the com

5条回答
  •  心在旅途
    2021-01-30 05:51

    Probably I'm too picky. In my book, the character(s) pointed to by a const char* can possibly be changed but not via the const char*. A const char * can point to modifiable storage. Example:

    char a[] = "abracadabra";
    const char * ccp = &a[0]; // ccp points to modifiable storage.
    *&a[0] = 'o'; // This writes to a location pointed to by const char* ccp
    

    So, my wording is:

    A char * is a pointer that be changed and that also allows writing through it when dereferenced via * or [].

    A const char * is a pointer that be changed and that does not allow writing through it when dereferenced via * or [].

提交回复
热议问题