在struct中动态初始化数组

时间:2018-05-03 11:18:49

标签: c

如何在struct Course中动态初始化数组?我需要制作一系列学生结构。

typedef struct {
  char *name; 
   char ID[9];

  } Student;

typedef struct {
  Student *students =  //here
} Course;

2 个答案:

答案 0 :(得分:2)

struct声明中初始化是不可能的,并且在C中没有意义 - 你还没有该结构的对象。

假设您的数组中需要可变数量的Student s,有不同的方法可以对其进行建模。典型的方法可能如下:

typedef struct {
    size_t capacity;
    size_t count;
    Student **students;
} Course;

使用双指针,这是为了保存Student对象的“引用”(而不是Student对象本身)。我必须猜测这就是你需要的。您可以分配和管理它,例如:

#define CHUNKSIZE 16  // reserve space for this many Students at once

Course *Course_create(void)
{
    Course *course = malloc(sizeof *course);
    if (!course) return 0;

    course->capacity = CHUNKSIZE;
    course->count = 0;
    course->students = malloc(CHUNKSIZE * sizeof *(course->students));
    if (!course->students)
    {
        free(course);
        return 0;
    }

    return course;
}

int Course_addStudent(Course *course, const Student *student)
{
    if (course->count == course->capacity)
    {
        // allocate more memory if needed
        size_t newcapa = course->capacity + CHUNKSIZE;
        Student **newstudents = realloc(course->students, newcapa * sizeof *newstudents);
        if (!newstudents) return 0; // error
        course->capacity = newcapa;
        course->students = newstudents;
    }
    course->students[course->count++] = student;
    return 1; // success
}

正确的清理可能如下所示:

void Course_destroy(Course *course)
{
    if (!course) return;
    free(course->students);
    free(course);
}

答案 1 :(得分:0)

Student *students只是指向Student的指针。您不能也不应该初始化指针。

<强>方法1

您需要先为结构分配内存,然后对其进行初始化。

// in main 
Course courses;
courses.students = malloc(sizeof(Student));
if (courses.students != NULL_PTR)
{
    courses.students.name = malloc(100);  // 100 would be the size of the name you want to store
    if (courses.students.name != NULL_PTR)
    {
        courses.students.name = "Default Name";
        courses.students.ID = 12345;
    }
}

<强>方法2

此方法首先从结构中删除指针。它改变了结构的定义。

由于没有涉及指针,您可以安全地在结构上初始化结构。

typedef struct {
  char name[100]; 
   char ID[9];

  } Student;

typedef struct {
  Student students;
} Course;


int main(void)
{
    Course courses = {{"Default Name",12345}};

    // other code here
}
相关问题