【问题标题】:Append won't work in Linked List of Arrays in C++追加在 C++ 中的数组链接列表中不起作用
【发布时间】:2015-02-10 12:12:11
【问题描述】:

这是我的课

class NumberList
{
private:
   // Declare a structure for the list
   struct ListNode
   {
      double value[10];           // The value in this node
      struct ListNode *next;  // To point to the next node
   }; 

   ListNode *head;            // List head pointer

public:
   // Constructor
   NumberList()
      { head = nullptr; }

   // Destructor
   ~NumberList();

   // Linked list operations
   void appendNode(double []);
   void insertNode(double []);
   void deleteNode(double []);
   void displayList() const;
};

这是我的附加功能,我无法让它工作——我不断收到一条错误消息。

void NumberList::appendNode(double num[])
{
   ListNode *newNode;  // To point to a new node
   ListNode *nodePtr;  // To move through the list

   // Allocate a new node and store num there.
   newNode = new ListNode;
   newNode->value = num;
   newNode->next = nullptr;

   // If there are no nodes in the list
   // make newNode the first node.
   if (!head)
      head = newNode;
   else  // Otherwise, insert newNode at end.
   {
      // Initialize nodePtr to head of list.
      nodePtr = head;

      // Find the last node in the list.
      while (nodePtr->next)
         nodePtr = nodePtr->next;

      // Insert newNode as the last node.
      nodePtr->next = newNode;
   }
}

错误信息:

prog.cpp: In member function ‘void NumberList::appendNode(double*)’: prog.cpp:40:19: error: incompatible types in assignment of ‘double*’ to ‘double [10]’ newNode->value = num;

关于我做错了什么有什么建议吗?

【问题讨论】:

  • 我想你想在 newnode->value 前面放一个 & 或者像 &newnode->value[0] 那样做,但我已经有一段时间没有使用 C++了。

标签: c++ arrays linked-list nodes


【解决方案1】:

void NumberList::appendNode(double num[]) 中的参数num 的类型实际上是一个指针 (= double*),而不是具有定义数量元素的数组。

在您的结构中使用std::array<double,10> 并作为appendNode 的参数将是一个很好的解决方案。

这个:

struct ListNode
{
  double value[10];
...

变成:

struct ListNode
{
  std::array<double,10> value;
...

你的函数参数将被声明为:

void appendNode(const std::array<double,10>& num);

newNode-&gt;value = num; 无需更改。

【讨论】:

  • 我将在哪里更改该声明 - newNode->value = num[];还是在函数参数中?
  • C 数组知道它们的大小(或者至少它构成了它们类型的一部分)。如果你将它们传递给一个接受指针的函数,它就会丢失。
  • 我不确定我是否做错了,但有人帮我完全重写了函数,它似乎对我不起作用。
  • @juanchopanza 澄清
  • 知道了——谢谢。还有一个问题——我已经更新了代码,现在在 main 中收到一条消息:运行时错误时间:0 内存:3424 信号:11。 NumberList list; double arr[10] = {1,2,3,4,5,6,7,8,9,0}; list.appendNode(arr);
猜你喜欢
  • 2018-07-28
  • 1970-01-01
  • 2015-06-04
  • 2017-03-09
  • 1970-01-01
  • 2016-07-23
  • 1970-01-01
  • 2020-08-31
  • 2017-05-05
相关资源
最近更新 更多