代码之家  ›  专栏  ›  技术社区  ›  onaclov2000

指针递增运算符错误

  •  4
  • onaclov2000  · 技术社区  · 14 年前

    我正在研究一个硬件问题,发现了一些对我来说很奇怪的事情。 这是有问题的函数和调用

    int find_oldest_frame(int **a, int size)
    {
       int min = clock();
       int **ptr;
       int *ptr2;
       int frame = 0;
       int i;
       // get address of pointer so we can modify it
       ptr = a;
       // store off original pointer location.
       ptr2 = *a;
    
       for (i=0; i<size; i++)
       {
    
          // Who is the oldest time
          if (**ptr < min)
          {
             min = **ptr;
             frame = i;
          }
          printf("Current_Pointer %d\n", *ptr);
          *ptr++; // For some reason ++ doesn't work.
    
       }
       // now store the oldest frame with the current system time, so it's no longer the oldest.
       *ptr = ptr2;
       *ptr += frame;
       **ptr = clock();
       *ptr = ptr2;
       // Return the array index so that we can change the right page!
       return frame;
    

    }

    所以长话短说,我得到一个弹出窗口(在windows中)说有问题,必须关闭。

    当我试图替换 *ptr++; 具有

    程序运行。 这让我很感兴趣所以我在gcc中使用-S 使用*ptr++版本,我得到以下指令:

    addl    $4, -20(%ebp)
    

    当*p+=1时,我得到

    movl    -20(%ebp), %eax
    movl    (%eax), %eax
    leal    4(%eax), %edx
    movl    -20(%ebp), %eax
    movl    %edx, (%eax)
    

    案例1

    增量-20%(ebp)乘以4(假设$4意味着)

    案例2

    我们将ebp中的内容存储到eax,

    (不知道()做了什么),但是再做一次?

    然后将地址从eax偏移量4加载到edx中,

    现在再次将ebp复制回eax,

    现在将edx复制到eax中,

    为什么?从我看到的东西中我缺少了什么?

    编辑:谢谢大家,我现在觉得很特别,真不敢相信我没有意识到!

    4 回复  |  直到 12 年前
        1
  •  6
  •   Wladimir Palant    13 年前

    这实际上是 operator precedence 之前 指针被取消引用,这意味着您增加指针的值(指针指向的内存),然后尝试取消引用它。这是调用未定义的行为,因为它指向单个 int .

    在后一种情况下 += 之后 解引用发生,因此您得到存储在指针内存中的值,然后将其添加到指针中。如果要使用postfix increment,则需要确保首先取消引用,可以使用:

    (*ptr)++;
    

        2
  •  2
  •   sharptooth    14 年前

    这个

    *ptr++; // For some reason ++ doesn't work.
    

    应该是

     (*ptr)++;
    

    *ptr++ 这样工作: *(ptr++)

     while( ( *t++ = *s++ ) != 0 );
    

    复制以空结尾的字符串。

        3
  •  2
  •   Frédéric Hamidi    14 年前

    *(ptr++);
    

    以及:

    (*ptr) += 1;
    

    *(ptr)++; 增加指针值并保持指针本身不变。

        4
  •  1
  •   Fred Foo    14 年前

    ++ 操作员有更高的 precedence * ,其优先级高于 += ++ 绑定到 ptr ,而 绑定到 (*ptr) .