簡體   English   中英

c指針雙指針

[英]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處拋出錯誤,表示datanext不是structureunion

您有兩個錯誤,一個是語法錯誤(應在使用點符號時使用箭頭符號),而另一個則與運算符優先級有關

選擇運算符->. 具有比取消引用運算符*更高的優先級。 這意味着表達式**ref->data等效於**(ref->data) 這當然是胡說八道,不會建立,因為data不是指針。

您有兩種選擇:

  1. 使用例如(*ref)->data
  2. 使用例如(**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.

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