首页 > 解决方案 > 错误:取消引用指向不完整类型“struct student”root->next->student_number = 17 的指针;

问题描述

//------libraries
#include <stdio.h>  //library for basic input/output
#include <stdlib.h> //library for memory allocations

//------structures
typedef struct{
    unsigned short int student_number;
    struct student *next;
}student;

int main( void){
    student *root;
    root = (student *)malloc(sizeof(student));

    root->student_number = 5;   //works
    printf("root student_number = %d\n", root->student_number);

    root->next = (student *)malloc(sizeof(student));
    root->next->student_number = 17;           //here is the problem
    printf("root->next = %d\n", root->next->student_number);
}

我创建了一个结构student。定义了一个指向链表第一个元素的根。有可能到达第一个链表元素(print root->student_number)。直到这里一切都很好:为链表的第二个元素分配了内存(root->next),但我不能为变量 student_number 赋值,分别打印。如何到达链表的第二个和下一个元素?会很高兴得到帮助:)

标签: cpointersstruct

解决方案


typedef编辑了一个匿名结构。 struct student不存在。尝试这个:

typedef struct student{
    unsigned short int student_number;
    struct student *next;
}student;

推荐阅读