#include<stdio.h>
int main(int argc,char *argv[])
{
int i=10;
void *k;
k=&i;
k++;
printf("%p\n%p\n",&i,k);
return 0;
}
++ 是对 void* 的合法操作吗?有些书说不是 但是 K & R 没有说任何关于 void * 算术的事情(K &R 2/e 的第 93,103,120,199 页)
请澄清。
PS:GCC 至少在 k++ 中没有提示。
最佳答案
这是一个GCC extension .
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.
如果您添加 -pedantic
标志,它将产生警告:
warning: wrong type argument to increment
如果您想遵守标准,请将指针转换为 char*
:
k = 1 + (char*)k;
标准规定不能对 void*
执行加法 (k+1
),因为:
指针运算是通过将
k
视为指向void
数组的第一个元素 (#0) 的指针来完成的 (C99 §6.5.6/7),k+1
将返回此“数组”中的元素 #1 (§6.5.6/8)。为了使这个有意义,我们需要考虑一个
void
数组。void
的相关信息是 (§6.2.5/19)The
void
type comprises an empty set of values; it is an incomplete type that cannot be completed.但是,数组的定义要求元素类型不能不完整(§6.2.5/20,脚注36)
Since object types do not include incomplete types, an array of incomplete type cannot be constructed.
因此 k+1
不能是一个有效的表达式。
关于c - void * 算术,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3922958/