用C正确铸造常量void指针为const char指针数组 [英] Casting const void pointer to array of const char pointers properly in C

查看:121
本文介绍了用C正确铸造常量void指针为const char指针数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有件C code的,看起来像这样:

I have a piece of C code that looks like this:

const char (*foo)[2] = bar();

现在巴()是一个返回(常量无效*)函数。如何正确施放此常量指针?在code从GCC会产生这样的警告:

Now bar() is a function that returns a (const void *). How do I properly cast this const pointer? The code produces this warning from GCC :

"initialization discards qualifiers from pointer target type".   

下面是我的一些不成功的尝试:

Here are some of my unsuccessful attempts:

const char (*foo)[2] = (const char *)bar();
const char (*foo)[2] = (const void **)bar();

原来的code不工作,我只是无法通过适当铸造返回值摆脱警告。

The original code does work, I just can't get rid of the warnings by properly casting the return value.

编辑:这已建议:

const char (*foo)[2] = (const char (*)[2])bar();

这似乎是正确的,但GCC给出了这样的警告:

It appears to be correct, but GCC gives this warning :

"cast discards qualifiers from pointer target type"   

这是几乎相同的原始警告

which is nearly identical to the original warning.

编辑2:好了,我想我已经得到了它。这里真正的问题是(常量无效*)定义栏()。在常量定义中的(为const char(*)[2])指的是数组的元素,不指针的阵列。这种类型的定义实际上是一个数组,再由无效指针psented $ P $时的常量。真正的答案是,(常量无效*)失去转换为<$ C $时,其劣势 T岬C>(为const char(*)[2])。

EDIT 2 : OK, I think I've got it. The real problem here is the ( const void * ) definition of bar(). The const in the definition (const char( * )[2]) refers to the elements of the array, not the pointer to the array. This type definition is essentially an array, which when represented by a void pointer is not const. The real answer is that a ( const void * ) loses its const-ness when cast to (const char ( * )[2]).

推荐答案

其他几个已经指出了正确的演员阵容,但它产生的伪警告
这一警告来自一个可能的错误 C标准,或(取决于您的跨pretation)的GCC应该特殊对待的情况。我相信常量预选赛可以安全地,毫不含糊地提升到数组类型。您可以删除该警告与 -Wno-铸QUAL 但当然,这将消除,你真正关心的情况下警告。

Several others have stated the correct cast, but it generates a spurious warning. That warning comes from a possible bug in the C standard, or (depending on your interpretation) a case that GCC should treat specially. I believe the const qualifier can be safely and unambiguously lifted to the array type. You can drop that warning with -Wno-cast-qual but of course that will eliminate warnings for cases that you actually care about.

要详细说明,类型为const char(*)[2] 表示指针常量数组(长度) 字符。数组没有标记常量,数组的只是元素。相比于键入常量无效* 时,编译器会认为后者是一个指向常量,其中作为前者是没有,从而产生该警告。 C标准没有提供方法来标记数组作为常量,即使常量阵列将相当于一个数组为const

To elaborate, the type const char (*)[2] means "pointer to array (length 2) of const char". The array is not marked const, just the elements of the array. When compared to the type const void *, the compiler notices that the latter is a pointer to const, where as the former is not, thus generating the warning. The C standard provides no way to mark an array as const, even though a const array would be equivalent to an array of const.

这篇关于用C正确铸造常量void指针为const char指针数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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