简体   繁体   English

这段与指针相关的代码有什么问题

[英]What is wrong in this code related to pointer

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

The above code in not working but when I take another pointer Node* h1=*head1;上面的代码不起作用但是当我使用另一个指针Node* h1=*head1; and then print its value its working fine.然后打印其工作正常的价值。 In both codes the value I want to print is same then why above code is wrong;在这两个代码中,我要打印的值是相同的,那么为什么上面的代码是错误的;

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

In this code snippet在此代码段中

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

    cout<<*head1->val;
}

the expression表达方式

*head1->val

is equivalent to相当于

*( head1->val )

(because the postfix operator -> has higher priority than the unary operator *) but the pointer head does not point to an object of the structure type. (因为后缀运算符->的优先级高于一元运算符*)但是指针head并不指向结构类型的object。 It points to another pointer, You have to write它指向另一个指针,你必须写

( *head1 )->val

This is equivalent to the expression with the intermediate variable h1这相当于带有中间变量h1的表达式

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

To make the difference more visible you can rewrite the expression of accessing the data member val the following way为了使差异更明显,您可以按以下方式重写访问数据成员val的表达式

( **head ).val

that is now the expression **head yields the lvalue of an object of the type struct Node .即现在表达式**head产生 object 类型的lvalue struct Node

Or using an intermediate variable like或者使用像这样的中间变量

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

Operator precedence puts -> before * .运算符优先级放在->之前* For illustration:举例说明:

#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;
}

The line marked as //error does not compile, beceause fpp has no member x .标记为//error的行无法编译,因为fpp没有成员x The other two lines print the same address, that of fx .另外两行打印相同的地址,即fx的地址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM