指针到常量用C转换 [英] pointer-to-const conversion in C

查看:189
本文介绍了指针到常量用C转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下code编译没有对海湾合作委员会警告,但给出了在Visual Studio 2005中的警告。

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指向一个常量字符指针。为什么要分配至P导致一个警告?

x points to a constant object of unknown type, and p points to a constant pointer to char. Why should the assignment to p result in a warning?

再次,这是C,而不是C ++。谢谢你。

Again, this is C, not C++. Thanks.

推荐答案

这是因为当你做一个类型的点的指针为另一种类型,有时,这样做是无意(错误),所以编译器警告你一下吧。

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。在我写的第一个地方的大部分的时间的是无意中做的,但AndreyT让我重新考虑它的时候,他理所当然地说,void *的专门为此目的存在。

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.

这篇关于指针到常量用C转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆