【问题标题】:Change the reference of a struct in C更改 C 中结构的引用
【发布时间】:2016-03-06 05:16:58
【问题描述】:

我有一段时间执行一些计算,我必须在一些节点中进行迭代。

我的结构是:

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 指向的位置,我的堆栈是否能够正确存储节点引用?我害怕失去访问节点的参考。

那么,如果我从堆栈中弹出节点,结果会是预期的吗?

我会遇到哪些问题?

【问题讨论】:

  • 我觉得你可以把你的代码写得更恰当一些,这样会更有意义。

标签: c pointers struct reference


【解决方案1】:

堆栈应该保留您对旧指针的引用,因此在 n 对它的引用上添加一个新指针不会丢失堆栈上的引用。似乎它会按预期工作。

【讨论】:

  • 谢谢。我正在检查它,但我不确定。 =)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-05
  • 1970-01-01
  • 2016-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多