非赋值加法后 C 指针发生变化

C pointer changes after non-assigning addition

我正在尝试了解如何使用 C 等语言实现闭包。

目前我想创建一个带有 intadder 函数,以及 returns 另一个也带有 int 参数的函数。调用返回的函数应该得到两个参数的总和。

这是伪代码示例:

fn adder(int lhs) {
    return fn (int rhs) {
        return lhs + rhs
    }
}

由于嵌套函数在标准 C 中不可用,我想我可以通过传递状态来实现它们。这是我的 C 实现:

#include <stdio.h>

typedef struct
{
    int *a; // This attribute should be a pointer as in my
            // ideal interpretation of closures, the state of
            // the parent function should be mutable within the child
} ClosureState;

int adder_inner(ClosureState state, int b)
{
    printf("a = %d\n", *state.a);
    return *state.a + b;
}

ClosureState make_adder(int a)
{
    ClosureState state = {
        .a = &a};

    return state;
}

int main()
{
    ClosureState adder_state = make_adder(5);
    int res1 = adder_inner(adder_state, 5);
    int res2 = adder_inner(adder_state, 10);
    int res3 = adder_inner(adder_state, 50);

    printf("%d, %d, %d\n", res1, res2, res3);
    return 0;
}

问题:adder_state 对象似乎在每次调用 adder_inner 后都会被修改,但我不明白为什么 *state.a 从未被重新分配。

上面代码的输出是:

$ clang -o clj clj.c && ./clj
a = 5
a = 10
a = 50
10, 20, 100

ClojureState (ClosureState) 没有理由持有一个指针。如果它只包含 int 本身会容易得多:

#include <stdio.h>

typedef struct
{
    int a; // No need for a pointer, the value can still be
           // changed in adder_inner() if needed.
} ClosureState;

int adder_inner(ClosureState *state, int b)
{
    printf("a = %d\n", state->a);
    return state->a + b;
}

ClosureState make_adder(int a)
{
    ClosureState state = {
        .a = a};

    return state;
}

int main()
{
    ClosureState adder_state = make_adder(5);
    int res1 = adder_inner(&adder_state, 5);
    int res2 = adder_inner(&adder_state, 10);
    int res3 = adder_inner(&adder_state, 50);

    printf("%d, %d, %d\n", res1, res2, res3);
    return 0;
}```