简体   繁体   中英

How -> operator is able to access structure data members whose name doesn't exist?

So I've created a binary tree data structure and I can't understand that how can you access pointer variables without their names?

Have a look at the code first

#include <stdio.h>
#include <stdlib.h>

struct node 
{
    int data;
    struct node *left, *right;
};

struct node *givetree()
{
    struct node *newnode = (struct node*)malloc(sizeof(struct node));
    char choice;
    
    printf("Enter data : ");
    scanf("%d",&newnode->data);
    
    printf("\nWanna fill left of %d ? (y/n) : ",newnode->data);
    scanf("%c",&choice);
    
    if(choice == 'y')
    newnode->left = givetree();
    
    printf("\nWanna fill right of %d ? (y/n) : ",newnode->data);
    scanf("%c",&choice);    

    if(choice == 'y')
    newnode->right = givetree();
    
    return newnode;
}

int main(void) {
    struct node *root = givetree();
    printf("\nThis works : %d",root->left->left->data);

    return 0;
}

So how the line printf("\nThis works: %d",root->left->left->data) works completely fine? The tree is created using recursion so the pointer named root receives a pointer to the root node, but how the pointer root is able to access structure data member named left if local variables names have been destroyed after the execution of function call?

I know they are present in the memory and retains their data but how we can access them if their names have been destroyed?

root is a pointer to struct node .

struct node has the members data , left , right . Consequently you can do these 3 accesses:

root->data
root->left
root->right

As left is a pointer to struct node , root->left is aa pointer to struct node . Consequently you can do these 3 accesses:

root->left->data
root->left->left
root->left->right

Once again root->left->left is aa pointer to struct node . Consequently you can do these 3 accesses:

root->left->left->data
root->left->left->left
root->left->left->right

And so on...and so on... As long as you don't exceed the depth of your binary tree.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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