更改 C 中结构体的引用

标签 c pointers struct reference

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

我的结构是:

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/

相关文章:

c - 函数变量的间接寻址

c - 指向函数的常量指针数组

arrays - 为什么数组大小未知?

c++ - 修改结构的函数不会更新结构

c - 在 C 中按字母顺序排序名称

c - POSIX `read()` 的 `buf` 应该是 `signed` 还是 `unsigned`?这有关系吗?

c - 打印两个数组中的公共(public)元素

c++ - 使用字符串作为指向其第一个字符的指针

c - 空指针赋值错误 union

C 如何在使用 struct* = struct 时解析不兼容指针类型的赋值