gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:13:28 24 4
gpt4 key购买 nike

#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 等其他符号,我能够从逻辑上想出这些符号来打印地址,但是在使用指向结构的指针来打印地址时,我不小心发现了它们,而不是能够从逻辑上来使用正确的符号。

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

最佳答案

I want to know whether whatever I have come up with is the correct usage to print the addresses of the member variables and if yes how is it the correct representation ?

是的,这是正确的。

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

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

It seems to be printing the correct addresses because I am able to access the values by dereferencing the address returned by &node1->next and &node1->data. *(&node1->next) and *(&node1->data) returns the values correctly.

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

关于c++ - 使用指向该结构的指针访问结构变量成员的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43941077/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com