为什么在 gcc 中允许 void 指针运算?
Why is void pointer arithmetic allowed in gcc?
尽管 void ptr
算法不标准,但以下代码正在使用 gcc 编译:
int main(){
int a = 5;
void* b = (void*) &a;
b++;
}
这是 GCC 支持的扩展。它将 void *
视为 char *
。
来自gcc docs:
6.24 Arithmetic on void
- and Function-Pointers
In GNU C, addition and subtraction operations are supported on
pointers to void
and on pointers to functions. This is done by
treating the size of a void
or of a function as 1.
A consequence of this is that sizeof
is also allowed on void
and on
function types, and returns 1.
这是因为 C 中最初没有 void
类型。取而代之的是 char
类型。并且 sizeof( char )
等于 1。
例如,我看到一个非常古老的遗留代码,其中写着
memset( ( char * )p, 0, n );
其中参数 p 的类型为 int *
。
看来这样做是为了向后兼容。
尽管 void ptr
算法不标准,但以下代码正在使用 gcc 编译:
int main(){
int a = 5;
void* b = (void*) &a;
b++;
}
这是 GCC 支持的扩展。它将 void *
视为 char *
。
来自gcc docs:
6.24 Arithmetic on
void
- and Function-PointersIn GNU C, addition and subtraction operations are supported on pointers to
void
and on pointers to functions. This is done by treating the size of avoid
or of a function as 1.A consequence of this is that
sizeof
is also allowed onvoid
and on function types, and returns 1.
这是因为 C 中最初没有 void
类型。取而代之的是 char
类型。并且 sizeof( char )
等于 1。
例如,我看到一个非常古老的遗留代码,其中写着
memset( ( char * )p, 0, n );
其中参数 p 的类型为 int *
。
看来这样做是为了向后兼容。