C中的指针操作和运算符优先级 [英] Pointer operations and operator precedence in C
问题描述
今天只和一个C家伙聊天,我们不同意以下几点:
Just had a chat with a C guy today and we disagreed on the following:
int intgA[2] = { 1, 2 };
int intgB[2] = { 3, 5 };
int *intAPtr = intgA;
int *intBPtr = intgB;
所以,当我们这样做时:
So when we do:
*intAPtr++ = *intBPtr++;
我的分析
第一:
intBPtr
递增1,现在指向地址5.
然后,遵从,保持值为5;
intBPtr
increments by one, now pointing to the address of 5.
Then, deference, holding the value 5;
intAPtr
也会加一,现在指向地址2.
随后引用,值为2;
intAPtr
also increments by one, now pointing to the address of 2.
Subsequently referencing and the value is 2;
最后:
2替换为5.
所以它们分别是:5和5.
So respectively they are: 5 and 5.
首先将*intBPtr
的值分配给*intAPtr
.
因此,它们变为:3和3.
Hence, they become: 3 and 3.
然后*intAPtr
和*intBPtr
都加1.
因此,它们分别变为:4和4.
So, respectively they become: 4 and 4.
我认为++
运算符比*
和=
都具有优先权,因此是我的主张.
I thought the ++
operator takes precedence both over *
and =
, hence my assertion.
例如,如果我们有:
*intAPtr++;
结果应该是2,对不对?因为我们先增加指针,然后取消引用.
The result should be 2, right? Because we first increment the pointer and then dereference.
那么,在他所说的情况下,为什么在上述情况下,我们首先将intBPtr
的值分配给intAPtr
的值,然后最后递增这些值?
So why in the above case, as he claims, we first assign the value of intBPtr
to the value of intAPtr
and increment the values last?
在这里接受了所有建议之后,我在IDE中运行了代码,结果确认了@sujin的代码:
尽管它确认我至少在优先次序方面是正确的:
Although it confirms that I was right at least in terms of precedence:
那个:*intAPtr++ = *intBPtr++;
intAPtr++
的优先级更高,这导致:intAPtr
将其地址加1.
intAPtr++
has a higher precedence, which leads to: intAPtr
increments its address by 1.
现在指向:2的地址.
同样:
intBPtr++
也会增加1(地址).
intBPtr++
also increments by 1 (address).
现在指向:5的地址.
然后轮到*
:
因此两者都分别被取消引用(*)到2和5.
So the both get dereferenced (*) to respectively 2 and 5.
但是问题仍然存在,因为上面的任务(=
)似乎没有发生.
But the problem exists still because the assignment above (=
) did not seem to take place.
如果同时执行,则两者都将变为5.
If it did both would become 5.
期待得到进一步的启发.
Looking forward to being further enlightened.
推荐答案
语句
*intAPtr++ = *intBPtr++;
解析为
*(intAPtr++) = *(intBPtr++);
并细分如下:
-
intBPtr
(3)当前指向的值分配给intAPtr
(intgA[0]
)指向的位置; - 指针
intAPtr
和intBPtr
递增.
- The value currently pointed to by
intBPtr
(3) is assigned to the location pointed to byintAPtr
(intgA[0]
); - The pointers
intAPtr
andintBPtr
are incremented.
发生这些事情的确切顺序是未指定;您不能依靠intBPtr
在intAPtr
之后递增,反之亦然,也不能依靠在增量之前发生的赋值,等等.
The exact order in which these things happen is unspecified; you cannot rely on intBPtr
being incremented after intAPtr
or vice-versa, nor can you rely on the assignment occuring before the increments, etc.
所以到intgA[0] == 3
和intAPtr == &intgA[1]
和intBPtr == &intgB[1]
都完成了.
So by the time this is all done, intgA[0] == 3
and intAPtr == &intgA[1]
and intBPtr == &intgB[1]
.
表达式a++
计算得出的值a
之前的增量.
The expression a++
evaluates to the value of a
before the increment.
这篇关于C中的指针操作和运算符优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!