簡體   English   中英

雙鏈表2

[英]Double linked list2

我已經做了很多鏈表,但是我有一段時間沒有使用它們,也沒有真正編程任何東西,因此我完全迷失了。 以下是我的代碼:

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

typedef struct
{
    int age; 
    int pers_num;
    char name[100];
    void *previous;
    void *next;
    
}Person;

int main(){
    Person first_element;
    Person last_element;
    first_element.next = (Person *)(&last_element);
    last_element.age = 19;
    printf("%d\n",(&last_element)->age);
    printf("%d\n",(first_element.next)->age);
    
    }

你能解釋一下為什么會拋出以下錯誤嗎?

speicher.c: In function 'main':
speicher.c:22:39: warning: dereferencing 'void *' pointer
   23 |     printf("%d\n",(first_element.next)->age);
      |                                       ^~
speicher.c:23:39: error: request for member 'age' in something not a structure or union

據我了解,“first_element.next”應該是指向last_element的指針。 因此,您應該能夠使用 -> 訪問 last_element 中的數據。 第 22 行運行完美,甚至認為它應該具有與第 23 行相同的 Output,其中引發了錯誤。

您不能取消引用 void 指針,因為它是一個引用 void 類型的指針:-) 換句話說,它並不真正知道它指向的實際類型。 這兩行表現不同的原因是,請記住a->b只是(*a).b語法糖:

printf("%d\n",(&last)->age);
    // This (&last)->age, which is actually the same
    // as last.age. In both cases, the type being used
    // to get the age field is Person, so no problem.

printf("%d\n",(first.next)->age);
    // This (first.next)->age is the same as
    // (*(first.next)).age. Because first.next is of type
    // void *, it cannot be dereferenced.

您所做的類似於用void x聲明一個變量,這是無效的(不要將其與有效的void *x混淆)。

您最好(在結構內)指向您想要的實際類型,例如:

typedef struct s_Person { // A
    int age; 
    int pers_num;
    char name[100];
    struct s_Person *previous, *next;
} Person; // B

請注意,在創建Person類型定義時不能使用它,因為它還不存在。 簡單地說,你可以認為它在B點出現。 命名結構s_Person存在於A中,因此可以在結構中使用。

暫無
暫無

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

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