【问题标题】:Incomlete type of structure problem with nested structures嵌套结构的不完全类型结构问题
【发布时间】:2019-08-11 20:26:43
【问题描述】:

我对结构没有什么问题。这是我的结构块:

#define STD_NAME 30
#define COURSE_LIMIT 10
#define COURSE_NAME 50
#define COURSE_CODE 6
#define COURSE_ACRONYM 8

typedef struct {
    int course_id;
    char* course_name[COURSE_NAME];
    char* course_code[COURSE_CODE];
    char* course_acronym[COURSE_ACRONYM];
    int quota;    
}course_t;

typedef struct {
    int std_id;
    char std_name[STD_NAME];
    double std_gpa;
    struct course_t* courses[COURSE_LIMIT]; //nesting part

}student_t;

我尝试使用嵌套结构和指针。 例如,为了获得课程配额,我在 main 函数中使用简单块,如下所示:

int main(void){

   student_t studentProfile;

    for(int i = 0; i < COURSE_LIMIT; i++)
    {
        printf("Enter the %d. course quota: ", i + 1);
        scanf("%d", &studentProfile.courses[i]->quota);
    }

    return 0;
}

但是当我编译这段代码时,我得到一个错误:

dereferencing pointer to incomplete type ‘struct course_t’
         scanf("%d", &studentProfile.courses[i]->quota);

我不知道如何修复“将指针延迟到不完整类型”,因为它与指针有点混淆。我应该使用内存分配吗?

【问题讨论】:

  • 你是否包含了你声明 struct course_t 的头文件?
  • 不,我只包括 stdio 和 stdlib。我认为不需要包含 course_t 的头文件,因为我已经在全局范围内创建了它。不是吗?

标签: c arrays pointers malloc structure


【解决方案1】:
typedef struct {
    int std_id;
    char std_name[STD_NAME];
    double std_gpa;
    struct course_t* courses[COURSE_LIMIT]; //nesting part
  //^^^^^^^^^^^^^^^^
}student_t;

此时没有struct course_t 这样的类型。只有course_t类型;它们不可互换。

那一行应该是

    course_t* courses[COURSE_LIMIT];

【讨论】:

  • 您没有初始化 student_profile.courses[i] 以指向任何东西,因此当您尝试取消引用未初始化的指针时遇到段错误也就不足为奇了。
  • studentProfile.courses[i]-&gt;quota = malloc(sizeof(int)); 这行得通吗?
  • 不,在将其指向任何东西之前,您再次取消引用 studentProfile.courses[i]。我相信你想要的东西更像studentProfile.courses[i] = malloc(sizeof course_t)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-19
  • 2017-02-19
相关资源
最近更新 更多