在C语言中,是否加入了一些我的指针的行为,增加了我的sizeof *(数据类型)是依赖编译器? [英] In C, whether the behavior of adding a number i to a pointer adds i*sizeof(datatype) is compiler dependent?

查看:180
本文介绍了在C语言中,是否加入了一些我的指针的行为,增加了我的sizeof *(数据类型)是依赖编译器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的伪code,当一个数i被添加到指针ABC,下一个数组索引指出。
我的应用预期作为编译器无关,并且还可以被用于不同的数据类型相似片段来工作。所以这是一个编译器相关的行为?

  DISP(无效* ABC)
{
   INT I = 0;
   INT N = 8;   对于(i = 0; I< N ++ I)
   {
      的printf(\\ N%D*((INT *)ABC + I));
   }
}诠释的main()
{
   INT ABC [] = {1,2,3,4,5};   DISP(ABC);
   返回0;
}


解决方案

不,你是安全的。它是由标准给出:

6.5.6加法运算符:


  

8时具有整型一个前pression被加上或减去
  从一个指针,其结果具有指针操作数的类型。如果
  操作数的指针指向数组对象的元素,数组
  是足够大的,结果指​​向一个元件从偏移
  原始的元素以使得的下标之差
  结果和原始的数组元素等于整数前pression。
  [...]


这基本上意味着,一个指向键入是PTED作为数组间$ P $ 键入以及加法和减法可以被看作是操作上这种阵列的索引。

既然你投的无效* 来一些有意义的东西是好的,因为指针获得reinter preTED。

In the following pseudo code, when a number i is added to the pointer abc, the next array index is pointed. My application is expected to work as compiler independent and also similar snippet may be used for different data types. So is this a compiler dependent behavior ?

disp( void* abc)
{
   int i = 0;
   int n = 8;

   for (i=0; i<n; ++i)
   {
      printf("\n %d",*((int*)abc+i) );
   }
}

int main()
{
   int abc[]={1,2,3,4,5,6,7,8};

   disp(abc);
   return 0;
}

解决方案

Nope, you are safe. It is given by the standard:

6.5.6 Additive operators:

"8. When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integer expression. [...]"

This basically means, that a pointer to a Type is interpreted as an array of Type, and additions and subtractions can be viewed as operations on the index of such an array.

Since you cast the void* to something meaningful it's ok, because the pointer gets reinterpreted.

这篇关于在C语言中,是否加入了一些我的指针的行为,增加了我的sizeof *(数据类型)是依赖编译器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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