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

标签 c pointers struct

我是 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 的指针的 inputsoutputs 数组,而不是 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/

相关文章:

c - setpgid 使交互式程序(vim,emacs ... ncurses?)无限循环

c - 带有指向数组指针的 printf scanf

c - 我应该将链表的头放在结构内部还是外部?

复制结构的内容在临时结构为 `free` d 后发生变化

c - C语言中如何让scanf一次只读取一个字符

c - 如何给通过指针运算计算出的内存地址赋值?

c - 循环外迭代器的声明和注册迭代器 : How useful they are?

c - 指针指针混淆

c - 将变量分配给结构体数组的成员时出现预期标识符或 '(' 错误

swift - 如何将变量从 ViewController 类传递到其他结构?