char* is a pointer to a char variable.

char* const is a constant pointer.

const char* is a pointer to a constant variable.

const char* const is a constant pointer to a constant.

char const* is the same as const char* . Automatically converted to it.

But about char* const* , the gcc (c99) compiler reasons like a separate type. Same with const char* const* . What is the meaning of * after const along with char* ? How to describe this type?

  • char* const* without const would be char** i. This is an array of constant strings. - nick_n_a
  • Such ads are easier to read from right to left. - Vladimir Gamalyan

3 answers 3

This is the same pointer to a pointer as char** , but you cannot change its address (the pointer pointed to by the variable).

  char* pc1 = (char*)malloc(LENGTH); strcpy(pc1, "Hello"); char* pc2 = (char*)malloc(LENGTH); strcpy(pc2, "World"); char* const* ppc1 = &pc1; // OK *ppc1 = pc2; // compile-time error char** ppc2 = &pc1; // OK *ppc2 = pc2; // OK 

    Deciphering such notation (and more severe, with the participation of function pointers, for example) sometimes helps the cdecl resource greatly

     char* const* x 

    const

    x is a pointer to a constant pointer to char

    - link

    x ( char* const* ) can be changed.
    *x ( char* const ) cannot be changed.
    **x ( char ) can be changed.

      A quote from Ben Clemens ’s book , Language C in the 21st Century (Chapter 8, Keyword const):

      Ads should be read right to left. In this way:

      • int const - constant integer;
      • int const * - (non-constant) pointer to a constant integer;
      • int * const is a constant pointer to a (non-constant) integer;
      • int * const * is a pointer to a constant pointer to integer;
      • int const * * - pointer to a pointer to a constant integer;
      • int const * const * is a pointer to a constant pointer to a constant integer.

      As you can see, the const qualifier always refers to what is to its left — just like * .

      You can rearrange the type name and const , that is, int const and const int are the same (although this trick with const and * will not succeed). I prefer the int const form because it is consistent with more complex constructs and the right-to-left reading rule. But the const int form is more common, perhaps because it is easier to pronounce in ordinary language (a constant integer) or because it has always been done this way. One way or another, both options are suitable.


      In article on Habré So you think you know Const? go a step further and add a third const qualifier:

      • int const * const * const is a constant pointer to a constant pointer to a constant integer.