【问题标题】:Pointer to pointer dereference; Compiler asking for '->'指向指针解引用的指针;编译器要求'->'
【发布时间】:2018-01-29 04:02:50
【问题描述】:

我编写了一个简单的函数来将一个子列表插入到由引用给出的链表中。代码对我来说看起来是正确的,但编译器指示我没有正确使用指针。

void insertSub(string h, day d, string gr, string sub, ListAPI **tmp_api) {
  auto newNode = new _ListSub;

  // initialize new node of sub-list
  newNode->h = h;
  newNode->d = d;
  newNode->gr = gr;
  newNode->sub = sub;

  // point new node to the previous and next node
  newNode->next = node->next;
  newNode->prev = node;

  // point actual node to the new node
  *tmp_api->head->next->prev = newNode;
  *tmp_api->head->next = newNode;

  cout << "New node inserted to " << *tmp_api->id << endl;

  // increment size
  ++ node->size;
}

在一些调用函数中,我使用它:

auto tmp_api = api;
insertSub( h, (day)enumerateDay(week), gr, sub, &tmp_api );

其中api 的类型为ListAPI *,并且确实包含节点。

g++ 错误:

../src/main.cpp:107:13: error: request for member ‘head’ in ‘* tmp_api’, which is of pointer type ‘ListAPI*’ (maybe you meant to use ‘->’ ?)
   *tmp_api->head->next->prev = newNode;
             ^~~~
../src/main.cpp:108:13: error: request for member ‘head’ in ‘* tmp_api’, which is of pointer type ‘ListAPI*’ (maybe you meant to use ‘->’ ?)
   *tmp_api->head->next = newNode;
             ^~~~
../src/main.cpp:110:51: error: request for member ‘id’ in ‘* tmp_api’, which is of pointer type ‘ListAPI*’ (maybe you meant to use ‘->’ ?)
   cout << "  $ newNode inserted to " << *tmp_api->id << endl;

【问题讨论】:

  • 我们需要看看你如何定义ListAPI,但head 会成为结构的成员似乎很奇怪。建议:将您的代码与此示例进行比较:learn-c.org/en/Linked_lists.
  • 您有运算符优先级问题。写(*tmp_api)-&gt;head

标签: c++ pointers dereference


【解决方案1】:

正如here 所见,-&gt; 运算符的优先级高于 * 运算符,因此首先对其进行评估。使用(*temp_api)-&gt;head

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多