0

I am new to c. I have a problem where I can't get two pointers to point to the same space in memory. Here is some code.

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

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

in the main I have

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*));

later in a nested for loop we have this

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

now when I change the value of IOList[i], shouldn't tempGate->inputs[j] change as well? If not why? How can I make this the case? Help me Codiwan You're my only hope.

  • You know, Codiwan Can Know C. :) – sfjac Apr 25 '15 at 00:06
  • Don't I need to allocate space for the pointers in tempGate->inputs even if they are pointing to the values in IOList? – FreeSandwiches Apr 25 '15 at 00:07
  • 1
    No, it shouldn't. If you set two things to the same value, and change one of them, the other doesn't change. There is no "entanglement". (And your `malloc`s are returning pointers to pointers to `struct IO`, which you cast to pointers to `struct IO`. That is not good, it leads to undefined programs.) – molbdnilo Apr 25 '15 at 00:10
  • 1
    Possibly unrelated to the problem you're experiencing, but [don't cast the return value of `malloc()`](http://stackoverflow.com/a/605858/3488231). – user12205 Apr 25 '15 at 00:13
  • `tempGate->inputs = IOList` will make those two pointers point to the same thing. Is that what you wanted? – yellowantphil Apr 25 '15 at 00:15

1 Answers1

3

You should make inputs and outputs arrays of pointers to IO, not arrays of IO. Then you can make the elements of this array point to elelemnts of 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*));

Then your loop should be:

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

Then when you change IOList[i].val, this will change the value of tempGate->inputs[j]->val.

Barmar
  • 741,623
  • 53
  • 500
  • 612