【问题标题】:Why am I getting non pointer type error in c++? [duplicate]为什么我在 C++ 中出现非指针类型错误? [复制]
【发布时间】:2021-01-20 17:35:21
【问题描述】:

我让 c++ 程序将数字作为输入,直到输入零并将它们保存为链表,然后打印出来,但我不明白为什么会出现这些错误。

代码如下:

#include <iostream>
using namespace std;

struct Node
{
   int data;
   Node* next;
};

int main()
{
   Node* head = NULL, temp1, temp2;
   int data = 1;
   while(data)
   {
      cout<<"Enter number or 0 if you want to end : "<<endl;
      cin>>data;
      temp1 = (Node*)malloc(sizeof(Node));
      temp2 = temp1;
      if(head==NULL)
         head = temp1;
      else
         temp2->next = temp1;
   }
   Node* temp1 = head->next;
   while(temp1->next != NULL)
   {
      cout<<temp1->data<<endl;
      temp1 = temp1 -> next;
   }
       return 0;
   }

我收到这些错误:

test.cpp: In function 'int main()':
test.cpp:18:41: error: no match for 'operator=' (operand types are 'Node' and 'Node*')
       temp1 = (Node*)malloc(sizeof(Node));
                                         ^
test.cpp:4:8: note: candidate: constexpr Node& Node::operator=(const Node&)
 struct Node
        ^~~~
test.cpp:4:8: note:   no known conversion for argument 1 from 'Node*' to 'const Node&'
test.cpp:4:8: note: candidate: constexpr Node& Node::operator=(Node&&)
test.cpp:4:8: note:   no known conversion for argument 1 from 'Node*' to 'Node&&'
test.cpp:21:17: error: cannot convert 'Node' to 'Node*' in assignment
          head = temp1;
                 ^~~~~
test.cpp:23:15: error: base operand of '->' has non-pointer type 'Node'
          temp2->next = temp1;
               ^~
test.cpp:25:10: error: conflicting declaration 'Node* temp1'
    Node* temp1 = head->next;
          ^~~~~
test.cpp:12:23: note: previous declaration as 'Node temp1'
    Node* head = NULL, temp1, temp2;
                       ^~~~~
test.cpp:26:15: error: base operand of '->' has non-pointer type 'Node'
    while(temp1->next != NULL)
               ^~
test.cpp:28:18: error: base operand of '->' has non-pointer type 'Node'
       cout<<temp1->data<<endl;
                  ^~
test.cpp:29:21: error: base operand of '->' has non-pointer type 'Node'
       temp1 = temp1 -> next;
                     ^~

【问题讨论】:

  • temp1 和 temp2 不是指针。 head 是一个指针。
  • Node* head = NULL, temp1, temp2; 行中,您定位* 的方式具有误导性。如果你这样写那行,你的错误会更明显:Node *head = NULL, temp1, temp2;
  • 一个定义,一个行的忠实粉丝。磁盘空间很便宜,可读性就像黄金一样。
  • C++ 有自己的内存管理(而且非常好),你不需要使用malloc
  • 您应该更喜欢new 而不是malloc。运算符new 调用构造函数,malloc 不调用。

标签: c++ pointers linked-list nodes


【解决方案1】:

这种方法会让您追加到列表的开头... 我不想给你直接的答案......但希望这会有所帮助!

分配节点: 带新节点()

将用户数据插入到新节点的数据变量中

让新节点指向头指针 (new_node->下一个)

重新调整头指针指向new_node(使其成为新头)

【讨论】:

    猜你喜欢
    • 2021-10-21
    • 2023-04-02
    • 2022-06-21
    • 2019-02-16
    • 2013-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多