[英]c pointers double pointers
#include<stdio.h>
#include<stdlib.h>
struct test
{
int data;
struct test *next;
};
void main()
{
struct test *head=(struct test *)malloc(sizeof(struct test));
struct test **ref=&head;
head->data=5;
head->next=NULL;
printf("\n %d \n %d",head->data,head->next);
printf("\n %d \n %d",**ref->data,**ref->next);
}
說明:
我已經嘗試了上面的代碼。
**ref
與*head
相同? 如果不是,為什么?
同樣,編譯器在第二個printf
處拋出錯誤,表示data
和next
不是structure
或union
。
您有兩個錯誤,一個是語法錯誤(應在使用點符號時使用箭頭符號),而另一個則與運算符優先級有關 。
選擇運算符->
和.
具有比取消引用運算符*
更高的優先級。 這意味着表達式**ref->data
等效於**(ref->data)
。 這當然是胡說八道,不會建立,因為data
不是指針。
您有兩種選擇:
(*ref)->data
(**ref).data
。 我將使用選項1作為ref
“引用” 指向結構的指針 ,該語法與您所做的工作更加內聯,IMO。
不相干的是,打印指針時不應使用"%d"
格式,而應使用"%p"
。 參見例如本printf
(和系列)參考 。
**ref
是指向struct test
的指針, *head
是指向struct test
的指針。
出現錯誤是因為引用時, **ref
屬於struct test
類型,應該使用點號.
獲得該結構的成員:
(**ref).data
head
是指向struct test
的指針,您可以在那里正確使用->
運算符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.