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 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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.