pointer-to-const conversion in C

前端 未结 6 943
傲寒
傲寒 2021-01-13 20:09

The following code compiles without warning on GCC but gives a warning in Visual Studio 2005.

const void * x = 0;
char * const * p = x;

x p

6条回答
  •  爱一瞬间的悲伤
    2021-01-13 20:16

    const void * x = 0;
    char * const * p = x;
    

    At first I assumed you meant to take the address of x and wrote the code for that. Then I decided that x points to a pointer to char []. Both anyway, and it's still quite confusing:

    #include 
    int main()
    {
            char s [] = "Hello World!";
            const void * x = s;
            const char * const * const p = (const char * const *)&x;
            printf("%s\n", *p);
    /* won't compile
            *p++;      // increments x to point to 'e'
            (**p)++;   // increments 'H' to 'I'
    */
            const char * y = s;
            x = &y;
            const char * const * const q = x;
            printf("%s\n", *q);
    /* won't compile
            *q++;
            (**q)++;
    */
            return 0;
    }
    

    The extra const before the char in the declaration of p prevents (**p)++ from compiling. However, the added const before the declaration of q (in GCC) shadows warning: dereferencing ‘void *’ pointer with error: increment of read-only location ‘**q’ for (**q)++. Hope that helps, it has helped me a little :-)

提交回复
热议问题