【问题标题】:Loop allocation of linked list inside inline struct not allocating memory内联结构内链表的循环分配不分配内存
【发布时间】:2013-05-06 10:56:11
【问题描述】:

我在循环中分配链表时遇到了奇怪的问题。

考虑一个简化的源代码:

struct main_s {
    minor_s minor_structure; (inline)
};

struct minor_s {
    list_s *first_dir;
};

struct list_s {
    anotherlist_s *first_object;
    list_s *next;
};

struct anotherlist_s {
    //multiple fields
};

我有一个基本的 init/deinit 函数,例如:

struct main_s *main_s_init();
void main_s_deinit();

现在我对循环分配感到困惑:

im passing to this function main_s->minor_structure.first_dir and, how_many parameter, defining how many linked nodes going to be initiated.

void loop_inittiation(struct list_s *list, int how_many) {
    int i;
    struct list_s *tmp = list;
    for(i = 0; i < how_many; i++) {
        tmp = malloc(sizeof(struct list_s));
        tmp = tmp->next;
    }
}

这就是我有问题的地方,我分配了临时的“tmp”而不是指向的结构。我知道要通过 tmp 分配指针,你必须使用双指针,但它仍然不起作用。我错过了什么?在 gdb 中没有分配内存空间:/。 我必须使用 **tmp 吗?

【问题讨论】:

    标签: c linked-list malloc structure inline


    【解决方案1】:

    你对哪里出了问题有正确的想法。函数中 tmp 的本地副本已更改,但是一旦您在外面,该值就会丢失。如果你想改变 C 中不同函数内的变量,你必须传递你想要改变的东西的地址。如果要更改的东西已经是指针,则必须传递指针(或双指针)的地址。如果要更改的是双指针,则必须传递三指针。如果是 123141 指针,则必须传递 123142 指针 :)

    把函数的参数改成:

    &(main_s->minor_structure.first_dir)
    

    只需将输入参数改为

    struct list **list
    

    将 tmp 更改为双指针以匹配它,然后每次使用 tmp 时,请确保添加额外的取消引用..

    struct list_s **tmp = list
    

    *tmp = malloc(sizeof(struct list_s));
    *tmp = (*tmp)->next;
    

    所以它看起来像:

    void loop_inittiation(struct list_s **list, int how_many) {
        int i;
        struct list_s **tmp = list;
        for(i = 0; i < how_many; i++) {
            *tmp = malloc(sizeof(struct list_s));
            tmp = &((**tmp)->next);
        }
    }
    

    另一种方法是将 tmp 内容单独保留,作为单个指针,存储您分配的第一个节点,然后直接说

    *list = tmp;
    

    但是您必须将第一次分配视为特殊情况。

    【讨论】:

    • 不幸的是,它在这个例子中不起作用,我在不是结构或联合的东西中收到对成员“下一个”的错误请求。将尝试弄清楚这一点。
    • 即使输入 *tmp = ((*tmp)->next);它编译但只重写结构中列表的第一个节点,而不是进入下一个。
    • 应该是tmp = &((**tmp)->next)?
    猜你喜欢
    • 1970-01-01
    • 2010-11-20
    • 2019-10-14
    • 2022-08-20
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2016-01-27
    相关资源
    最近更新 更多