繁体   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