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