【问题标题】:Initialising an array of structure nested inside an array of structure in C初始化嵌套在C中的结构数组中的结构数组
【发布时间】:2020-08-03 23:02:26
【问题描述】:

目的是在另一个结构的另一个数组中包含一个结构数组。两个结构数组都应该单独声明和初始化。建议的问题和答案同样只有我的问题的一个组成部分,但没有这个或类似的组合。 我在此处添加的代码只是一个简化示例。所有数组大小和元素在执行之前都是已知的。

这是示例代码,无法编译“Segmentation fault”:

#include <stdio.h>
#include <string.h>

struct student_course_detail
{
    int  course_id;
    char course_name[50];
};

struct student_detail 
{
    int id;
    char name[20];
    // structure within structure
    struct student_course_detail *course[2]; 
}stu_data[2], *stu_data_ptr[2];


struct student_course_detail course_data[2] = {
  {71145, "Course 1"}, 
  {33333, "Course 2"},
}; 

struct student_detail stu_data[2] = {
    {1, "Anna", &course_data[1]},
    {2, "Tom", &course_data[2]}
};


int main() 
{
    stu_data_ptr[2] = &stu_data[2];

    printf(" Id is: %d \n", stu_data_ptr[0]->id);
    printf(" Name is: %s \n", stu_data_ptr[0]->name);


    printf(" Course Id is: %d \n", 
                         stu_data_ptr[0]->course[0]->course_id);
    //printf(" Course Name is: %s \n", 
    //                 stu_data_ptr[0]->course[0]->course_name);
    //printf(" Course Id is: %d \n", 
    //                     stu_data_ptr[0]->course[1]->course_id);
    //printf(" Course Name is: %s \n", 
    //                  stu_data_ptr[0]->course[1]->course_name);

    return 0;
}

代码示例链接:https://www.onlinegdb.com/Hk2NQ42OU

【问题讨论】:

    标签: c arrays pointers structure


    【解决方案1】:

    结构成员course 是一个由两个指向struct student_course_detail 的指针组成的数组。

    从你尝试初始化它的方式来看,它不应该是一个数组,而是一个指向struct student_course_detail的普通指针:

    struct student_course_detail *course;  // Pointer to a single student_course_detail structure
    

    你在其他地方也有类似的问题(stu_data_ptr)。

    另外不要忘记数组索引是 0 基数,所以&amp;course_data[2] 超出了course_data 数组的范围。

    【讨论】:

    • 我让代码按照我想要的方式运行。 (根据您的提示)link 但我仍然收到警告:main.c:32:18: warning: assignment from in compatible pointer type 如何正确分配此指针?
    【解决方案2】:

    当你定义一个包含 n 个元素的数组时,元素的索引范围是 0 到 n-1。

    所以在这种情况下,所有数组的大小都是 2,因此您拥有的元素由 0 和 1 索引。

    例如这是非法的:

    stu_data_ptr[2] = &stu_data[2]; //illegal
    

    你应该可以这样做:

    stu_data_ptr[1] = &stu_data[1];
    

    stu_data_ptr[0] = &stu_data[0];//use this, since you use stu_data_ptr[0] later
    

    【讨论】:

      猜你喜欢
      • 2015-04-13
      • 1970-01-01
      • 1970-01-01
      • 2012-05-02
      • 1970-01-01
      • 2010-09-23
      • 2010-12-06
      • 1970-01-01
      相关资源
      最近更新 更多