【问题标题】:What is wrong in this code related to pointer这段与指针相关的代码有什么问题
【发布时间】:2020-05-16 09:48:17
【问题描述】:
/* The structure of the Linked list Node is as follows:

struct Node
{
    int val;
    struct Node *next;

    Node(int data){
        val = data;
        next = NULL;
    }

}; 
*/

void intersection(Node **head1, Node **head2,Node **head3)
{

    cout<<*head1->val;
}

上面的代码不起作用,但是当我使用另一个指针 Node* h1=*head1; 然后打印它的值时它工作正常。在这两个代码中,我要打印的值是相同的,那么为什么上面的代码是错误的;

/* The structure of the Linked list Node is as follows:

struct Node
{
    int val;
    struct Node *next;

    Node(int data){
        val = data;
        next = NULL;
    }

}; 
*/

void intersection(Node **head1, Node **head2,Node **head3)
{

    Node* h1=*head1;
    cout<<h1->val;
}

【问题讨论】:

  • 请附上minimal reproducible example 并解释“不工作”是什么意思
  • @idclev463035818 这不是完整的代码。注释块只是为了让读者清楚了解链表的结构

标签: c++ c++11 pointers operator-precedence dereference


【解决方案1】:

在这段代码中sn-p

void intersection(Node **head1, Node **head2,Node **head3)
{

    cout<<*head1->val;
}

表达式

*head1->val

等价于

*( head1->val )

(因为后缀运算符 -> 比一元运算符 * 具有更高的优先级)但指针 head 不指向结构类型的对象。它指向另一个指针,你必须写

( *head1 )->val

这相当于带有中间变量h1的表达式

Node* h1 = ( *head1 );
h1->val;

为了使差异更明显,您可以重写访问数据成员val的表达式,如下所示

( **head ).val

现在的表达式**head 产生lvalue 类型的对象struct Node

或者使用中间变量,比如

Node *h1 = *head;
( *( h1 ) ).val
     ^
     |
   *head

【讨论】:

    【解决方案2】:

    运算符优先级将-&gt; 放在* 之前。举例说明:

    #include<iostream>
    
    struct foo {
        int x;
    };
    
    int main() { 
        foo f;
        foo* fp = &f;
        foo** fpp = &fp;
    
        auto& xref = f.x;
    
        std::cout << &xref << "\n";
        //std::cout << *fpp->x;      // error
        std::cout << &(*fpp)->x;
    }
    

    标记为//error 的行无法编译,因为fpp 没有成员x。另外两行打印相同的地址,即f.x

    【讨论】:

      猜你喜欢
      • 2011-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-30
      相关资源
      最近更新 更多