我有一段时间执行一些计算,并且必须在某些节点中进行迭代。
我的结构是:
typedef struct {
int pointer;
int *n; //an array
} ENTRY;
typedef struct {
int nofentries; //number of entries
RENTRY *entries; //array of entries
} NODE;
我的职能是:
NODE *choose_node(NODE *currentnode, ENTRY *input) {
NODE *n;
//it copies a node by using memcpy (including its struct fields)...
n = node_clone(currentnode);
while(true) {
//my computation to choose a entry....
if(my computation is true)
return n;
//my doubt is here:
//I have a stack that stores the visited elements
//the push function does NOT copy the NODE
//it aims only to store the references
stack_push(stack, n);
//then we update the node for the next level
//this function gets other node (it returns a pointer of a new NODE)
n = get_node(n->entries[entry]->pointer);
}
}
如果我更改 n 指向的位置,我的堆栈是否能够正确存储节点引用?我担心的是丢失访问节点的引用。
那么,如果我从堆栈中弹出节点,结果会是预期的吗?
我在这里会遇到哪些问题?
最佳答案
堆栈应该保留对旧指针的引用,因此将新指针放在 n 对它的引用上不会丢失堆栈上的引用。看起来它会按预期工作。
关于更改 C 中结构体的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35823421/