使用指向结构变量成员的指针访问该结构的成员的地址

Accessing address of members of a struct variable using pointer to that structure

本文关键字:成员 结构 指针 访问 地址 变量      更新时间:2023-10-16
#include<iostream>
using namespace std;
int main()
{
struct node
{
int data;
struct node *next;
};
struct node *node1;
struct node node2;
node2.data = 200;
node2.next = NULL;
cout<<"address of node2: "<<&node2<<endl;
cout<<"address of node2.data: "<<&node2.data<<endl;
cout<<"address of node2.next: "<<&node2.next<<endl;
cout<<"value of node2 data: "<<node2.data<<endl;
cout<<"value of node2 next is: "<<node2.next<<endl;
node1 = (struct node*)malloc(sizeof(node));
node1->data = 100;
node1->next = NULL;
cout<<"value of node1 data: "<<node1->data<<endl;
cout<<"value of node1 next: "<<node1->next<<endl;
cout<<"address of node1 variable is: "<<&node1<<endl;
cout<<"address of node1 data variable is: "<<&node1->data<<endl;
cout<<"address of node1 next variable is: "<<&node1->next<<endl;
cout<<"value stored at node1 variable is: "<<node1<<endl;
}

我想使用指向该结构的指针打印结构变量成员的地址。从上面的代码示例中可以看出,我使用了 &node1->next 和 &node1->data 来打印地址。它似乎打印了正确的地址,因为我能够通过取消引用 &node1->next 和 &node1->data 返回的地址来访问这些值。*(&node1->next) 和 *(&node1->data) 正确返回值。

但我不明白符号"&node1-> data"和"&node1->next"是如何返回结构变量成员的地址的。我不小心发现 &node1->data 和 &node1->next 打印了地址。而对于 &node2.data 和 &node2.next 等其他符号,我能够在逻辑上提出打印地址的符号,但是在使用指向结构的指针打印地址时,我不小心发现了它们,而不是能够逻辑地想出正确的符号。

我想知道我想出的是否是打印成员变量地址的正确用法,如果是,它的正确表示方式如何?

我想知道我想出的是否是打印成员变量地址的正确用法,如果是,它如何是正确的表示?

是的,这是正确的。

间接寻址运算符或"arrow"->返回对指向对象成员的引用。因此,运算符地址的参数&是成员。adderess-of 返回该对象的地址,即成员的地址。因此,从逻辑上讲,获取成员地址的正确方法是首先应用箭头运算符来获取对象,然后是运算符的地址,如下所示:

auto* pointer_to_object = get_the_object();
auto* address_of_member = &pointer_to_object->name_of_member;

它似乎正在打印正确的地址,因为我能够通过取消引用&node1->next&node1->data返回的地址来访问这些值。*(&node1->next)*(&node1->data)正确返回值。

这应该是很明显的。取消引用操作与地址操作相反,因此按顺序应用这两个操作将相互抵消。*&node1->data等价于node1->data,它确实会返回成员的值。