C语言中的指针和变量之间的区别? [英] Differences between pointers and variables in C?
问题描述
#include <stdio.h>
int inc1(int x) { return x++; }
int inc2(int *x) { return (*x)++; }
int
main(void)
{
int a;
a = 3;
printf("%d\n", inc1(a) + a);
printf("%d\n", inc2(a) + a);
return 0;
}
我正在研究过去的论文,其中一个问题是跟踪第6行和第9行之间对a所做的更改.我有点理解指针(指的是内存位置),但是如果有人可以通过在这段代码中所做的更改非常棒.
I'm working through a past paper and one of the questions is to track the changes made to a between lines 6 and 9. I kind of understand pointers (referencing to memory location) but if someone could just talk me through the changes made to a throughout this piece of code that would be great.
推荐答案
我将解释这个几乎相同的代码,其中不包含您的帖子中的错误:
I'll explain this nearly identical code that doesn't contain the error in your post:
#include <stdio.h>
int inc1(int x) { return x++; }
int inc2(int *x) { return (*x)++; }
int main(void) {
int a;
a = 3;
printf("%d\n", inc1(a) + a);
printf("%d\n", inc2(&a) + a);
return 0;
}
a
初始化为3,然后将 a 的值传递给inc1()
,该值将其返回并使用 post-increment 加1.这意味着返回的实际值仍为3.
a
is initialized to 3, then the value of a is passed to inc1()
, which returns it and adds 1 using post-increment. This means the actual value returned is still 3.
接下来, a 的地址被传递到inc2()
.这意味着x中的值发生了什么变化.同样,使用后增量,所以inc2()
返回的是3,但是在调用之后,a
是4.
Next, the address of a is passed to inc2()
. That means that what happens to the value in x happens to a. Again, post-increment is used, so what inc2()
returns is 3, but after the call, a
is 4.
但是,编译器可以自由地在序列点之间以任何顺序求值诸如a
或inc2(&a)
的表达式.这意味着inc2(&a) + a
右边的a
可以是3或4(取决于a
是在int2(&a)
之前还是之后进行求值的,因此程序可以输出 6 7 >或 6 6 .
However, compilers are free to evaluate expressions, such as a
or inc2(&a)
, in any order between sequence points. This means that the a
on the right of inc2(&a) + a
may be either 3 or 4 (depending on whether a
is evaluated before or after int2(&a)
, so the program may output either 6 7 or 6 6.
这篇关于C语言中的指针和变量之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!