void *的算术 [英] void * arithmetic
问题描述
#包括LT&;&stdio.h中GT;
INT主(INT ARGC,CHAR *的argv [])
{
INT I = 10;
无效* K;
K =&放;我; ķ++;
的printf(%P \\ n%P \\ N,&安培; I,K);
返回0;
}
++是一个法律上的操作无效*?有些书上说,这不是
但K&放大器; R不吭声就无效*算术(PG K&放93103120199; R 2 / E)
请澄清一下。
PS:GCC不至少以K +抱怨。
这是一个 GCC扩展一>
在GNU C,加法和减法运算支持指针为void和函数指针。这是由治疗
空洞的大小做
或功能1
块引用>如果您添加
-pedantic
标志会产生警告:
警告:错误类型的参数来递增
块引用>如果你想遵守此标准,铸就指针
的char *
:K = 1 +(字符*)K;
本标准规定一个人不能执行加法(
K + 1
)的无效*
,这是因为:
指针运算是由处理
K
作为指针的第一个元素(#0)的数组无效<中/完成code>(C99§6.5.6/ 7),和
K + 1
将返回元素#1在这个阵列(§6.5.6/ 8)为了使这个意义上说,我们需要考虑
的数组无效
。为无效
相关信息是(§6.2.5/ 19)
的
无效
类型包括空值的集合;这是一个不完整的类型无法完成。
块引用>然而,数组的定义要求中的元素类型不能是不完整的(§6.2.5/ 20,脚注36)
由于对象类型不包括不完全类型,不完全类型的数组不能被建造。
块引用>因此,
K + 1
不可能是一个有效的前pression。#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; }
Is ++ a legal operation on void* ? Some books say that it's not but K & R doesn't say anything regarding void * arithmetic ( pg. 93,103,120,199 of K &R 2/e)
Please clarify.
PS : GCC doesn't complain at least in k++.
解决方案It is a 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.If you add the
-pedantic
flag it will produce the warning:
warning: wrong type argument to increment
If you want to abide to the standard, cast the pointer to a
char*
:k = 1 + (char*)k;
The standard specifies one cannot perform addition (
k+1
) onvoid*
, because:
Pointer arithmetic is done by treating
k
as the pointer to the first element (#0) of an array ofvoid
(C99 §6.5.6/7), andk+1
will return element #1 in this "array" (§6.5.6/8).For this to make sense, we need to consider an array of
void
. The relevant info forvoid
is (§6.2.5/19)The
void
type comprises an empty set of values; it is an incomplete type that cannot be completed.However, the definition of array requires the element type cannot be incomplete (§6.2.5/20, footnote 36)
Since object types do not include incomplete types, an array of incomplete type cannot be constructed.
Hence
k+1
cannot be a valid expression.这篇关于void *的算术的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!