c - 一个简单的 C 程序的奇怪输出

标签 c

我在 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/

相关文章:

c - 使用基本修剪示例在 C 中释放内存

c - 字符串回文检查

连接二进制数

抛硬币程序问题,C 编程

c++ - 蚊子 : publish message to broker

c - C 中的文件输入

c++ - qemu-系统-i386 : Error loading uncompressed kernel without PVH ELF Note

c - 在 C 中,如何将 String 类型和 int 类型存储在同一个变量中?

c++ - CRYPT_INTEGER_BLOB 到十进制字符串

c - 变量不保存函数的返回值