簡體   English   中英

-> 運算符如何能夠訪問名稱不存在的結構數據成員?

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

所以我創建了一個二叉樹數據結構,我不明白你怎么能訪問沒有名字的指針變量?

先看看代碼

#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;
}

那么printf("\nThis works: %d",root->left->left->data)這行是如何工作的呢? 樹是使用遞歸創建的,因此名為root的指針接收到指向根節點的指針,但是如果在執行 function 調用后局部變量名稱已被銷毀,指針 root 如何能夠訪問名為left的結構數據成員?

我知道它們存在於 memory 中並保留了它們的數據,但如果它們的名稱已被銷毀,我們如何訪問它們?

root是指向struct node的指針。

struct node有成員dataleftright 因此,您可以執行以下 3 種訪問:

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

由於left是指向struct node的指針, root->left是指向struct node的指針。 因此,您可以執行以下 3 種訪問:

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

root->left->left再次是指向struct node的指針。 因此,您可以執行以下 3 種訪問:

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

等等......等等......只要你不超過二叉樹的深度。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM