问题描述
在 Visual Studio C++ 版本 9(可能还有其他版本)中,以下代码:
In Visual Studio C++ version 9 (and probably other versions too), the following code:
int a = sizeof(void);
void const *b = static_cast<void const *>("hello world");
b += 6;
error C2070: 'void': illegal sizeof operand
error C2036: 'const void *' : unknown size
此代码在 GCC 下工作,它处理 sizeof(void)
as 1
.
This code works under GCC, which treats sizeof(void)
as 1
.
有什么办法可以绕过这个限制,因为为了指针算术的目的显式地强制转换为 char *
增加了混乱(void *
被很好地识别并用作指向原始内存的无类型指针).
Is there some way around this limitation, as casting explicitly to char *
for purposes of pointer arithmetic adds to the confusion (void *
is well recognised and used as a typeless pointer to raw memory).
- 请注意,我很清楚标准的存在.
- 我想要做原始指针算术.
- 我把
sizeof(void)
表明我很清楚这个事实它不是1
是问题的原因. - 代码示例只是为了演示什么需要生成错误.
- 我知道这不是使用
void
的正常"方式,但这是 C,并且会发生这些事情. - 是的,人们需要在低级别执行此操作.我不是在追求为什么,我在追求如何.如果您想知道原因,请查看一些内核源代码或您友好的 glibc.
- Please note, I'm well aware of theexistence of the standard.
- I want to do raw pointerarithmetic.
- I take
sizeof(void)
toshow that I'm well aware the factthat it isn't1
is thecause of the problem. - The codeexample is simply to demonstrate whatis required to generate the errors.
- I know this isn't a "normal" way to use
void
, but this is C, and these things happen. - Yes, people need to do this at low-level. I'm not after why, I'm after how. If you want to know why, take a look at some kernel source, or your friendly glibc.
这个问题似乎引起了很大的混乱.问题不在于为什么sizeof(void) == 1
不是标准的,而是当它不是标准时该怎么办.
It seems this question has generated a great deal of confusion. The question is not about why having sizeof(void) == 1
is not standard, but what to do when it isn't.
在要进行单字节指针运算的情况下,结果证明强制转换为 char *
是正确答案,而不是因为 *(void *)
没有大小,但因为标准实际上保证 *(char *)
总是 1
.因此,char *
的使用总是正确的,并且与 void *
与 GCC 扩展一致,用于原始指针算法.
In the instance that single-byte pointer arithmetic is to be done, it turns out that casting to char *
is the correct answer, not because *(void *)
has no size, but because the standard actually guarantees that *(char *)
is always 1
. Therefore the use of char *
is always correct, and congruent with void *
with the GCC extension for the purposes of raw pointer arithmetic.
为了进一步强调这一点,void *
是指向无类型内存的指针的正确选择,char *
是转换为 的正确类型,用于原始指针算术.
To further reinforce the point, void *
is the correct choice for pointers to typeless memory, and char *
is the correct type to cast to for raw pointer arithmetic.
推荐答案
它会出现 正确答案 是使用 char *
进行指针运算,因为 sizeof(char)
始终定义为 1,并且在任何平台上都具有最好的可寻址粒度.
It would appear the correct answer is to use char *
for pointer arithmetic, because sizeof(char)
is always defined to be 1, and to be of the finest addressable granularity on any platform.
所以简而言之,没有办法绕过限制,char *
实际上是正确的方法.
So in short, there is no way around the limitation, char *
is in fact the proper way to do it.
Matthias Wandel 拥有 正确答案,但理由不同.
Matthias Wandel had the right answer but with a different justification.
这篇关于void 大小未知时的指针运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!