我是 c 的新手。我有一个问题,我无法让两个指针指向内存中的同一空间。这是一些代码。
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 你是我唯一的希望。
最佳答案
您应该制作指向 IO
的指针的 inputs
和 outputs
数组,而不是 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
的值。
关于c - 我无法弄清楚我的指针错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29859437/