c++ - 此代码与指针相关的错误

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

/* 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;
}

最佳答案

在此代码段中

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

关于c++ - 此代码与指针相关的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61834856/

相关文章:

c++ - 为什么在删除适配器的默认 IP 时 DeleteIPAddress 会失败?

c++ - 匹配 clang/gcc 中的所有 GNU C SIMD vector 扩展类型

c++ - 将作用域枚举转换为 int

c - 为什么在使用 ncurses 时不能有一个成员名为 "refresh"的结构?

C++ 传递临时堆栈对象作为对函数的引用

将指针转换为整数

c++ - Boost 库队列问题

C++ MFC Picturebox 改变位图

c++ - munmap_chunk:使用 std::vector 更改数据存储位置时的无效指针

c++ - __STDC_VERSION__ 未在 C++11 中定义?