在C中正确地将const void指针转换为const char指针数组 [英] Casting const void pointer to array of const char pointers properly in C
问题描述
我有一个C代码看起来像这样:
I have a piece of C code that looks like this:
const char (*foo)[2] = bar();
现在 bar()
返回(const void *)
。如何正确转换这个 const
指针?代码从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();
原来的代码工作,我只是不能摆脱警告,
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 void *)
定义 bar()
。定义(const char(*)[2])
中的 const
指的是数组的元素,指向数组的指针。这个类型定义本质上是一个数组,当由 void
指针表示 const
。真正的答案是,(const void *)
失去其 cons
t-ness当转换为(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 cons
t-ness when cast to (const char ( * )[2])
.
推荐答案
其他几个人已经说明了正确的转换,但它生成虚假警告。
此警告来自可能的错误 C标准,或(取决于您的解释)GCC应特别对待的情况。我相信 const
限定符可以安全和明确地提升到数组类型。您可以使用 -Wno-cast-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]
表示 const
char
。数组没有标记为 const
,只是数组的元素。当与类型 const void *
比较时,编译器注意到后者是指向 const
的指针,其中前者不是,从而产生警告。 C标准没有办法将数组标记为 const
,即使 const
数组等价于数组 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中正确地将const void指针转换为const char指针数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!