我在 C 中有以下内容:
int x = 0;
int *a = &x;
void foo(int *a)
{
static int x = 0;
x++;
*a += x;
a = &x;
*a = x + 10;
}
int _tmain(int argc, _TCHAR* argv[])
{
foo(a);
foo(a);
printf("%d\n", *a);
return 0;
}
我可以清楚地调试它并看到行 *a += x
没有做任何事情而且我可以看到 x 的值在函数退出前一秒钟是 22
并打印出 13
。
当我在脑海中计算时,我得到了 34,据我所知,这应该是正确的答案。 有人可以解释我可能哪里错了吗?
最佳答案
让我们一步一步来。
第一轮:
int x = 0; // global "x"
static int x = 0; // local "x" = 0
x++; // local "x" = 1
*a += x; // global "x" += local "x" results in global "x" = 1
a = &x; // local "a" points to local "x"
*a = x + 10; // local "x" = local "x" + 10 results in local "x" = 11
第二轮:
int x = 0; // global "x" = 1 now
static int x = 0; // local "x" = 11 now
x++; // local "x" = 12
*a += x; // global "x" += local "x" results in global "x" = 13
a = &x; // local "a" points to local "x"
*a = x + 10; // local "x" = local "x" + 10 results in local "x" = 22
printf("%d\n", *a); // prints global "x", 13
关于c - 一个简单的 C 程序的奇怪输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14955844/