void *的算术 [英] void * arithmetic

查看:189
本文介绍了void *的算术的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 #包括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 )的无效* ,这是因为:


  1. 指针运算是由处理 K 作为指针的第一个元素(#0)的数组无效<中/完成code>(C99§6.5.6/ 7),和 K + 1 将返回元素#1在这个阵列(§6.5.6/ 8)


  2. 为了使这个意义上说,我们需要考虑的数组无效。为无效相关信息是(§6.2.5/ 19)


      

    无效类型包括空值的集合;这是一个不完整的类型无法完成。



  3. 然而,数组的定义要求中的元素类型不能是不完整的(§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) on void*, because:

  1. Pointer arithmetic is done by treating k as the pointer to the first element (#0) of an array of void (C99 §6.5.6/7), and k+1 will return element #1 in this "array" (§6.5.6/8).

  2. For this to make sense, we need to consider an array of void. The relevant info for void is (§6.2.5/19)

    The void type comprises an empty set of values; it is an incomplete type that cannot be completed.

  3. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆