![](/img/trans.png)
[英]If a variable is a pointer to a structure, then which operator is used to access data members of the structure through the pointer variable?
[英]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
有成員data
, left
, right
。 因此,您可以執行以下 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.