【问题标题】:Ref/DeRef a double pointed link listRef/DeRef 一个双指向链接列表
【发布时间】:2018-06-14 23:16:33
【问题描述】:

我正在传递一个链接列表,其中包含另一个链接列表到一个函数,但是我在从传递的双指针中取消/引用内部链接列表时遇到问题。此处push(*config->inner_linked_list... 行的编译器错误为'*config' is a pointer; did you mean to use '->'。内部主要&config->inner_linked_list 工作正常。我似乎无法确定我需要在这里使用哪种类型的 ref/deref。

typedef struct new_inner {
    wchar_t setting[10];
    wchar_t val[10];
    struct new_inner  * next;
}INTLL_t ;

typedef struct new_head {
    wchar_t name[10];
    struct INTLL_t * inner_linked_list;
    struct new_head * next;
} HEAD_t;




// In Main
int main(){
...
    HEAD_t * config;
    config = malloc(sizeof(HEAD_t));
    config = NULL;

//config populated elsewhere

    functo1(&config);
...
}


BOOL functo1(HEAD_t ** config){
    HEAD_t * current = *config;
    while(current != NULL){

    INTLL_t * s = another_ll; // Also INTLL_t
    while(s != NULL){


    push(*config->inner_linked_list, another_ll->setting,another_ll->val);
            s = s->next;
    }

    current = current->next;
}

return TRUE;
}

【问题讨论】:

  • config = malloc(sizeof(NODE_t)); 你是说sizeof(HEAD_t) 吗? NODE_t 没有在你的代码中定义?
  • 我做了,已编辑。谢谢

标签: c pointers linked-list double-pointer


【解决方案1】:
    struct INTLL_t * inner_linked_list;

struct INTLL_t 是未定义的类型。它与 INTLL_t 无关(这是一个 typedef,而不是一个结构)。您在这里的意思可能是INTLL_t *struct new_inner *

    HEAD_t * config;
    config = malloc(sizeof(NODE_t));
    config = NULL;

这是内存泄漏。您刚刚丢失了指向malloc 返回的块的唯一指针。此外,NODE_t 未定义。无论如何,它应该是config = malloc(sizeof (HEAD_t)) 或(最好)config = malloc(sizeof *config)

BOOL functo1(HEAD_t ** config){

BOOL 未定义。

    NODE_t * s = another_ll;

NODE_tanother_ll 均未定义。

    push(*config->inner_linked_list, another_ll->setting,another_ll->val);

push 未定义。

config 是一个指向结构体的指针。 *a->b 解析为*(a->b),这要求a 是指向其b 成员也是指针的结构的指针(它相当于*((*a).b))。你想要(*config)->inner_linked_list 代替(或等效(**config).inner_linked_list)。

return TRUE;

TRUE 未定义。

【讨论】:

  • 感谢您的回复和您的时间。
  • 我一直试图在这里锻炼内存泄漏的逻辑。是因为执行 sizeof(NODE_t) 还是因为 NODE_t 未定义。 (* NODE_t 是一个错字。应该是 HEAD_t)或在 malloc 调用后设置“config = NULL”没有做我认为的那样?
【解决方案2】:

通过指针操作符访问成员 -> 比解引用操作符 * 具有更高的优先级,因此当您执行 *config->inner_linked_list 时,它会尝试访问 HEAD_t 的双指针成员,这将导致错误。它在 main 中工作,因为那里的配置对象是一个普通的指针。您需要括号才能正确使用。

(*config)->inner_linked_list

http://en.cppreference.com/w/c/language/operator_precedence

【讨论】:

    猜你喜欢
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多