ona*_*000 4 c operator-precedence
好吧,这个让我很困惑.我正在研究硬件问题,并发现了一些对我来说非常奇怪的东西.这是函数和调用问题
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;
Run Code Online (Sandbox Code Playgroud)
}
因此,为了使长话短说,我得到的,说有一个问题,必须关闭弹出窗口(在Windows).
当我尝试替换*ptr ++;*ptr + = 1;
该程序运行.这让我感兴趣,所以我在GCC随着*PTR ++版本我得到这个指令使用-S:
addl $4, -20(%ebp)
Run Code Online (Sandbox Code Playgroud)
*p + = 1我得到了
movl -20(%ebp), %eax
movl (%eax), %eax
leal 4(%eax), %edx
movl -20(%ebp), %eax
movl %edx, (%eax)
Run Code Online (Sandbox Code Playgroud)
对我来说,这看起来像一个非常相似的操作,所以假设我正确读到这个,
情况1
将-20(%ebp)增加4(假设$ 4表示)
案例2
我们将ebp中的内容存储到eax中,
(不确定()做什么),但又做了吗?
然后将eax偏移量的地址从4加载到edx中,
现在再次将ebp复制回eax,
现在将edx复制到eax中,
我的意思是看起来他们做同样的事情,但出于某种原因*ptr ++!=*ptr + = 1
为什么?我看到的是什么?
编辑:感谢大家现在我觉得特别,我不敢相信我没有意识到这一点!
这实际上是运算符优先级的问题.在取消引用指针之前应用后缀增量运算符,这意味着您递增指针的值(它指向的内存),然后尝试取消引用它.这是调用未定义的行为,因为它指向单个行为int.
在后一种情况下,在取消引用发生后+=应用,因此您获得存储在指针内存中的值,然后添加到它.如果要使用后缀增量,则需要确保首先出现取消引用,您可以使用以下命令:
(*ptr)++;
Run Code Online (Sandbox Code Playgroud)
而不是你现在拥有的.