-2

对于基本数据类型,指针如何在 C 中递增?我无法理解为什么下面代码中的差异没有给我内存位置的字节差异,它给了我 1..

      Here is my code:: 
          char c1='c';
          char *c=&c1;
          int i1=1;
          int *i=&i1;
          long l1=1;
          long *l=&l1;
          float f1=1.1;
          float *f=&f1;
          double d1=1.3;
          double *d=&d1;
          printf("c =%u ,c +1=%u\n",c,c+1);
          printf("i =%u ,i +1=%u\n",i,i+1);
          printf("l =%u ,l +1=%u\n",l,l+1);
          printf("f =%u ,f +1=%u\n",f,f+1);
          printf("d =%u ,d +1=%u\n",d,d+1);

          printf("c diff =%u\n",(c+1)-(c));
          printf("i diff =%d\n",(i+1)-(i));
          printf("l diff =%u\n",(l+1)-(l));
          printf("f diff =%u\n",(f+1)-(f));
          printf("d diff =%u\n",(d+1)-(d));

          printf("c diff =%u\n",(c)-(c+1));
          printf("i diff =%u\n",(i)-(i+1));
          printf("l diff =%u\n",(l)-(l+1));
          printf("f diff =%u\n",(f)-(f+1));
          printf("d diff =%u\n",(d)-(d+1));

    Output::c =1636923 ,c +1=1636924
    i =1636896 ,i +1=1636900
    l =1636872 ,l +1=1636876
    f =1636848 ,f +1=1636852
    d =1636820 ,d +1=1636828
    c diff =1
    i diff =1
    l diff =1
    f diff =1
    d diff =1
    c diff =4294967295
    i diff =4294967295
    l diff =4294967295
    f diff =4294967295
    d diff =4294967295

    Why I am not getting "i diff =%d\n",(i+1)-(i) ==>> 4      
4

4 回答 4

1
Why I am not getting "i diff =%d\n",(i+1)-(i) ==>> 4

因为它在大多数情况下是这样的:

(i+1) - (i) / sizeof(int) 

等于 1。

但是您应该注意,正如 C 标准中引用的那样,这没有定义,对于指针减法工作,指针应该指向同一个数组中的元素或刚好超出它:

来自 C11 标准(6.5.6 第 9 段)

当两个指针相减时,都应指向同一个数组对象的元素,或者指向数组对象的最后一个元素;结果是两个数组元素的下标之差。

于 2013-08-26T01:21:14.993 回答
1

这里有几件事:当您进行指针运算时,您不是在处理字节,而是在处理 X*sizeof(pointertype)。当您说 (i+1)-i 时,您不是在执行“多少字节”操作,而是取回两点之间的指针位置数。这是指针位置的差异。

于 2013-08-25T20:35:34.040 回答
1

指针运算始终以指向类型为单位。这不仅意味着在p + 1内部添加sizeof(*p)到内存地址(这是您在前 4 行中看到的),而且还p - q告诉您两个指针之间有多少项目,而不是有多少字节。最后四个数字约为 40 亿,因为用于这些计算的类型是无符号的,因此下溢:p+1大于p,因此p - (p+1)为负数。

于 2013-08-25T20:36:56.603 回答
1

我无法理解为什么以下代码中的差异没有给我字节差异

因为没有指定这样做。

它给了我 1

如果你将 1 加到 X 并减去 X,你会得到 1。这是算术定律。C具有“指针算术”并且它遵守算术定律(如果定义了所讨论的操作)。这里没有什么大惊喜。

于 2013-08-25T21:00:51.367 回答