增量运算阵列上的错误指针? [英] Increment operator on pointer of array errors?
问题描述
我想很简单的东西,好应该是简单的,但不知何故与我搞乱...
I'm trying something very simple, well supposed to be simple but it somehow is messing with me...
我想,当为数组处理时作为指针和指针处理,以了解++阵列上的效果。
I am trying to understand the effect of ++ on arrays when treated as pointers and pointers when treated as arrays.
因此,
int main()
{
int a[4] = { 1, 4, 7, 9 };
*a = 3;
*(a+1) = 4;
*++a = 4; //compiler error
}
1 因此,在 *(A + 1)= 4
我们设置一个[1] = 4; //快乐
但是,当 * + A = 4;
,我期望指针以递增之一,因为++是precedent为*然后*在踢我们使其等于4。但这code刚刚为什么不工作...?
1: So at *(a+1)=4
we set a[1]=4; //Happy
But when *++a = 4;
, I'd expect pointer a to be incremented one since ++ is precedent to * and then * kicks in and we make it equal to 4. But this code just does not work... Why is that?
另一个问题:
int main()
{
int* p = (int *)malloc(8);
*p = 5;
printf("%d", p[0]);
*++p = 9; //now this works!
printf("%d", p[1]); //garbage
printf("%d", p[0]); //prints 9
}
2 立即* ++ P = 9;工作正常,但它不是真正的表现就像一个数组。如何是两个不同的?这只是递增p和使它等于9。如果我打印P [0],它现在打印9和我看到,虽然不能经由p访问[0]了,*(P-1)示出了5仍然存在。所以,用索引[0],正是它指向一个指针?发生了什么变化?
2: Now *++p = 9; works fine but it's not really behaving like an array. How are two different? This is just incrementing p, and making it equal to 9. If I print p[0], it now prints 9 and I see that though can't access it via p[0] anymore, *(p-1) shows 5 is still there. So indexing a pointer with [0], where exactly does it point to? What has changed?
非常感谢各位专家!
推荐答案
数组名是不可修改的左值那么操作++不会因此适用 ++中的
试图修改 A
是编译时错误(其中 A
是数组名)。
The array names is not modifiable lvalue so operation ++ is not applied hence ++a
that try to modify a
is compilation time error (where a
is array name).
请注意 *(A + 1)
和 *一个++
不一样的, A + 1
是因为它只需添加一个有效的指令 1
,但不修改 A
本身,而 ++中的
(即equvilent到 A = A + 1
)尝试修改,因此错误。
Note *(a + 1)
and *a++
are not same, a + 1
is a valid instruction as it just add 1
but doesn't modify a
itself, Whereas ++a
(that is equvilent to a = a + 1
) try to modify a hence error.
请注意数组名'是的不的指针。指针是可变的,但数组名都没有。的,当然,当你在最前pressions数组名指定数组名的指针,然后衰变为第一个元素的地址。例如。
Note 'array names' are not pointer. Pointers are variable but array names are not. Of-course when you assign array name to a pointer then in most expressions array names decays into address of first element. e.g.
int *p = a;
请注意 P
点( A [0]
)。
这是前pression A [I]
等同于 *(A + I)
,其中 A
可以是指针或数组名。因此,在你的第二个例子 P [I]
有效期的前pression。
An expression a[i]
is equivalent to *(a + i)
, where a
can be either a pointer or an array name. Hence in your second example p[i]
is valid expression.
此外, * ++ P
是有效的,因为,因为 P
是第二个$指针(变量) C $ç例子。
Additionally, *++p
is valid because because p
is a pointer (a variable) in second code example.
这篇关于增量运算阵列上的错误指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!