【问题标题】:Failed to add node on Chained List无法在链表上添加节点
【发布时间】:2014-01-09 18:11:04
【问题描述】:

我想创建一个链表,初始化它并在开头添加一个新节点。 但是我有这个问题:

//// 错误:在不是结构或联合的东西中请求成员“值” ////

t_bool list_add_elem_at_front(t_list *front_ptr, double elem)
{
  if (front_ptr == NULL)
    {
      front_ptr = malloc(sizeof(*front_ptr));

      front_ptr->value = elem;
      front_ptr->next = NULL;
    }
  printf("%f\n", front_ptr->value);
  return (TRUE);
}

我确定结构是 malloc,但我真的不明白为什么它在结构上找不到“值”和“*next”

int main(void)
 {
  int i = 2.1;

  t_list list_head = NULL;
  list_add_elem_at_front(&list_head, i);
 }

还有头文件

typedef struct  s_node
{
    double          value;
    struct s_node   *next;
}               t_node;

typedef t_node   *t_list;

【问题讨论】:

    标签: c list pointers


    【解决方案1】:

    试试这个

    t_bool list_add_elem_at_front(t_list *front_ptr, double elem)
    {
      if (*front_ptr == NULL)
        {
          *front_ptr = malloc(sizeof(**front_ptr));
    
          (*front_ptr)->value = elem;
          (*front_ptr)->next = NULL;
        }
      printf("%f\n", (*front_ptr)->value);
      return (TRUE);
    }
    

    【讨论】:

    • 谢谢老兄,它确实有效。请问可以解释一下吗?
    • 你需要为这个解决方案做malloc(sizeof(**front_ptr))
    • @Laykker 就你的代码而言,front_ptr 是指针to list_head。需要取消对实际的引用。
    • int i = 2.1; --> double i = 2.1;
    • 真的很有帮助,非常喜欢你!
    【解决方案2】:

    在:

    t_bool list_add_elem_at_front(t_list *front_ptr, double elem)
    

    参数中的指针过多:

    t_list *front_ptr
    

    当你把它与:

    typedef t_node   *t_list;
    

    导致t_node**

    我不会在参数中删除*,而是在任何地方都使用t_node *

    【讨论】:

    • 我知道,但我想这样做
    • @Laykker - 我看到你想使用 typedef - 取消引用 t_list * 会起作用,但如果你不这样做,你的代码会更清晰(可能还有你的错误消息) '不要以这种方式使用指针typedefs
    【解决方案3】:

    另外问题在于 sizeof 的参数应该是 t_node

    【讨论】:

    • 你确定吗?
    • @(Glen Teitelbaum) 是的,但不是唯一的问题
    • 只是注意到这个问题不会导致://// error: request for member ‘value’ in something not a structure or union ////
    • @(Glen Teitelbaum) 你是对的,但在 C 语言中问题并不总是单独出现:-)
    • 声明“另外,问题出在参数中...”可能更清楚,然后显示正确的代码。顺便说一句,我可以把我的 'n' 拿回来吗?
    猜你喜欢
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-10
    • 1970-01-01
    相关资源
    最近更新 更多