为什么在这种情况下输出为“0”?
Why is the output `0` in this case?
#include <stdio.h>
int main(void)
{
int i;
int *p = (int *) malloc(5 * sizeof(int));
for (i=0; i<10; i++)
*(p + i) = i;
printf("%d ", *p++);
return 0;
}
所以,我运行这个代码。现在我在这里被告知 (在接受的答案中) *p++
将首先增加指针然后取消引用它。因此,在上面的代码中,指针不应该先递增然后取消引用,因此输出应该是 1
吗?相反,输出结果为 0
。为什么?
这条语句
printf("%d ", *ptr++);
执行以下操作:
- 取消引用
ptr
,得到 ptr[0]
的值
- 打印出
int
步骤 1 的计算结果,即 ptr[0]
- 增加
ptr
所以它指向 ptr[1]
要打印出 ptr[1]
使用:
printf("%d ", *++ptr);
请注意,它是 post 增量。这样,postfix ++
运算符的返回值就是操作数本身的值,那么作为副作用,操作数对象的值就是递增。
表达式 *ptr++
将是
*ptr
- 使用
*ptr
的值作为printf("%d ", *ptr);
ptr = ptr + 1
此类表达式的输出可以理解为:
- Precedence of prefix ++ and
*
is same. Associativity of both is right to left.
- Precedence of postfix ++ is higher than both
*
and prefix ++. Associativity of postfix ++ is left to right.
Therefore, in the above code, shouldn't the pointer be incremented first and then de-referenced and hence output should be 1?
使用以下要求:
printf("%d ", *++ptr);
你的优先级部分是对的,但让我们看看后缀增量运算符 属性,好吗?
C11
标准在第 6.5.2.4 章中说,后缀递增和递减运算符
The result of the postfix ++
operator is the value of the operand. As a side effect, the value of the operand object is incremented (that is, the value 1 of the appropriate type is added to it). [...]
因此,变量本身会经历增量的影响,但是存在变量(带有后缀增量)的语句将 avail 变量的现有值,而不是增量值。增量将在稍后部分作为副作用执行。
首先,您应该添加#include <stdlib.h>
。其次,您应该更正您的代码 int *p = (int *) malloc(10 * sizeof(int));
。然后 *p++
代表 1. printf *p; 2. p++
。如果你想得到值1,你应该使用代码printf("%d ", *++p);
。希望对您有所帮助。
#include <stdio.h>
int main(void)
{
int i;
int *p = (int *) malloc(5 * sizeof(int));
for (i=0; i<10; i++)
*(p + i) = i;
printf("%d ", *p++);
return 0;
}
所以,我运行这个代码。现在我在这里被告知 *p++
将首先增加指针然后取消引用它。因此,在上面的代码中,指针不应该先递增然后取消引用,因此输出应该是 1
吗?相反,输出结果为 0
。为什么?
这条语句
printf("%d ", *ptr++);
执行以下操作:
- 取消引用
ptr
,得到ptr[0]
的值
- 打印出
int
步骤 1 的计算结果,即ptr[0]
- 增加
ptr
所以它指向ptr[1]
要打印出 ptr[1]
使用:
printf("%d ", *++ptr);
请注意,它是 post 增量。这样,postfix ++
运算符的返回值就是操作数本身的值,那么作为副作用,操作数对象的值就是递增。
表达式 *ptr++
将是
*ptr
- 使用
*ptr
的值作为printf("%d ", *ptr);
ptr = ptr + 1
此类表达式的输出可以理解为:
- Precedence of prefix ++ and
*
is same. Associativity of both is right to left.- Precedence of postfix ++ is higher than both
*
and prefix ++. Associativity of postfix ++ is left to right.Therefore, in the above code, shouldn't the pointer be incremented first and then de-referenced and hence output should be 1?
使用以下要求:
printf("%d ", *++ptr);
你的优先级部分是对的,但让我们看看后缀增量运算符 属性,好吗?
C11
标准在第 6.5.2.4 章中说,后缀递增和递减运算符
The result of the postfix
++
operator is the value of the operand. As a side effect, the value of the operand object is incremented (that is, the value 1 of the appropriate type is added to it). [...]
因此,变量本身会经历增量的影响,但是存在变量(带有后缀增量)的语句将 avail 变量的现有值,而不是增量值。增量将在稍后部分作为副作用执行。
首先,您应该添加#include <stdlib.h>
。其次,您应该更正您的代码 int *p = (int *) malloc(10 * sizeof(int));
。然后 *p++
代表 1. printf *p; 2. p++
。如果你想得到值1,你应该使用代码printf("%d ", *++p);
。希望对您有所帮助。