简体   繁体   English

指向成员结构的指针如何工作?

[英]How pointer to member struct work?

I am beginner in c++ and I want to question about how pointer to member struct work. 我是C ++的初学者,我想问一下指向成员struct的指针如何工作。 Here I have code: 这里我有代码:

struct Node
{
    int data;
    Node* next;     // next variable store address of Node.

    void Print()
    {
        cout <<"Value in next variable is: " <<&next;
    }
};

int main()
{
    Node Sample;
    sample.data = 5;
    cout <<"Data is: " <<sample.data <<"\n";
    sample.Print();
    cout <<"Address of Sample is: " <<&Sample <<"\n";
}

Output: 输出:
Data is: 5 数据为:5
Value in next variable is: 0xbf9b6758 下一个变量的值是:0xbf9b6758
Address of Sample is: 0xbf9b6754 示例的地址是:0xbf9b6754

In this case pointer variable next has different address with &Sample . 在这种情况下,指针变量next&Sample具有不同的地址。 How this work? 这个如何运作? Why they have different address? 为什么他们有不同的地址?

You are not printing the value of next. 您没有打印next的值。 You take the address of next (by printing &next ). 您可以获取下一个地址(通过打印&next )。 The address of the member next is the address is simply ((char *)&Sample) + offsetof(Node, next) . 成员next的地址是简单的((char *)&Sample) + offsetof(Node, next) Ie the address of Sample plus the position of the member relative to the start of the struct. 即Sample的地址加上成员相对于结构开始的位置。

The value of next could be printed by leaving out the & operator: cout << next , however you never set the value of next to begin with, so its value will be arbitrary. 可以通过省略&运算符来打印next的值: cout << next ,但是您永远不会设置next的值,因此它的值是任意的。

Answer to query: 查询答案:

Value in next variable is: 0xbf9b6758 
Address of Sample is: 0xbf9b6754

These 4 steps learn you what is happening arround? 这四个步骤将学习您正在发生的事情?

step 1: firstly, structure var sample is declared. 步骤1:首先,声明结构var sample。

step 2: As sample is created into memory ,members of sample is initialized with default values. 步骤2:在将样本创建到内存后,样本成员将使用默认值初始化。

step 3: becoz next is a pointer variable so, it will also initialized with some garbage value( ie next unused address in Ram). 步骤3: becoz next是一个指针变量,因此,它还将使用一些垃圾值(即Ram中的下一个未使用的地址)进行初始化。

step 4: next pointer holds the address - 0xbf9b6758 because, 步骤4:下一个指针保存地址0xbf9b6758因为,

"size of sample variable is = sum of sizes of each member of struct node" “样本变量的大小是=结构节点每个成员的大小之和”

= size of data + size of next =数据大小+下一个大小

= 2 + 2 => 4 = 2 + 2 => 4

KeyPoint --> Size of next is 2 byte because Addresses in memory are of unsigned integer format(datatype) KeyPoint-> next的大小为2个字节,因为内存中的地址为无符号整数格式(数据类型)

So, next variable is assigned the different address from sample variable. 因此,下一个变量被分配了与样本变量不同的地址。

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

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