我无法弄清楚我的指针错误

I can't figure out my pointer error

我是 c 的新手。我有一个问题,我无法让两个指针指向内存中的相同 space。这是一些代码。

struct IO{
    int val;
    char* name;
};

struct Gate{
    enum GateType type;
    struct Gate* next;
    int numInputs;
    struct IO* outputs;
    struct IO* inputs;
};

我主要有

struct Gate* tempGate;
tempGate = (struct Gate*)malloc(sizeof(struct Gate));
struct IO* IOList;
IOList = (struct IO*)malloc(sizeof(struct IO)*20);

tempGate->inputs = (struct IO*)malloc(sizeof(struct IO*)*2);
tempGate->outputs = (struct IO*)malloc(sizeof(struct IO*));

稍后在嵌套的 for 循环中我们有这个

tempGate->inputs[j] = IOList[i];

现在当我改变 IOList[i] 的值时,tempGate->inputs[j] 不应该也改变吗?如果不是为什么?我怎样才能做到这一点?帮我 Codiwan 你是我唯一的希望。

您应该创建 inputsoutputs 指向 IO 的指针数组,而不是 IO 的数组。然后你可以让这个数组的元素指向 IOList.

的元素
struct Gate{
    enum GateType type;
    struct Gate* next;
    int numInputs;
    struct IO** outputs;
    struct IO** inputs;
};

tempGates->inputs = malloc(sizeof(struct IO*)*2);
tempGates->outputs = malloc(sizeof(Struct IO*));

那么你的循环应该是:

tempGate->inputs[j] = &(IOList[i]);

然后当你改变IOList[i].val时,这将改变tempGate->inputs[j]->val的值。