pointer-to-const conversion in C

前端 未结 6 938
傲寒
傲寒 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:21

    It happens because when you make a pointer of one type point to another type, sometimes it is done unintentionally (bug), so the compiler warns you about it.

    So, in order to tell the compiler that you actually intent to do it, you have to do explicit casting, like this:

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

    P.S. At the first place I wrote "most of the times is done unintentionally", but AndreyT made me reconsider it when he rightfully said that void * exists specifically for that purpose.

提交回复
热议问题