简体   繁体   English

C:链接列表节点的malloc(结构内的结构)

[英]C: malloc for linked list node (struct within struct)

I'm having difficulties using malloc to dynamically allocate memory when creating linked list nodes. 创建链接列表节点时,我很难使用malloc动态分配内存。

For my assignment, we MUST use the following struct definitions: 对于我的作业,我们必须使用以下结构定义:

typedef struct course {
    char *name;
    BST students;
} Course;

typedef struct courseNode {
    Course data;
    struct courseNode *next;
} *CourseList;

The CourseList structs are the actual linked list nodes, while the Course structs contain the name of the course and a binary search tree of students enrolled. CourseList结构是实际的链接列表节点,而Course结构包含Course名称和已注册学生的二进制搜索树。 You'll notice the struct Course is inside the struct CourseList . 您会注意到struct Course在struct CourseList内部。

I need to create a new CourseList node, given a string to use as the name field of the inner Course struct, using dynamic allocation based on the length of the string. 我需要创建一个新的CourseList节点,并给定一个字符串用作内部Course结构的name字段,并使用基于字符串长度的动态分配。 I've tried all combinations of mallocing the outer and inner structs based on the string's length, but I can't seem to get the name string properly copied into the inner struct. 我已经尝试过根据字符串的长度来分配外部结构和内部结构的所有组合,但是我似乎无法正确地将name字符串复制到内部结构中。 I'm sure there's an easy answer, but I'm not finding it. 我敢肯定有一个简单的答案,但是我找不到。

I've tried all combinations of mallocing the outer and inner structs based on the string's length, but I can't seem to get the name string properly copied into the inner struct. 我已经尝试过根据字符串的长度来分配外部结构和内部结构的所有组合,但是我似乎无法正确地将名称字符串复制到内部结构中。

That's because the length of the string does not change the way you allocate your struct , which has a fixed size. 这是因为字符串的长度不会更改分配具有固定大小的struct的方式。 String needs to be allocated separately, and assigned to name member of data member of CourseList : 字符串需要单独分配,并分配给CourseList data成员的name成员:

CourseList newNode = malloc(sizeof(*newNode));
newNode->data.name = malloc(strlen(name)+1);
strcpy(newNode->data.name, name);

Note the asterisk in front of newNode . 注意newNode前面的星号。 This is because CourseList is a pointer type. 这是因为CourseList是指针类型。

Well if you really want to malloc the struct based on the string length: 好吧,如果您真的想根据字符串长度来分配结构:

  /* Assuming newname is a const char * with the course name,
   * course_head is the start of the linked, list,
   * and students should be zero initialized */
  CourseList newNode = malloc(sizeof CourseList);
  Course newCourse = malloc(sozeof(Course) + strlen(newname) + 1);
  memset(newCourse->students, 0, sizeof(BST));
  newCourse->name = (char *)newCourse + sizeof(newCourse);
  strcpy(newCourse->name, newname);
  newNode->data = newCourse;
  newNode->next = course_head;
  course_head = newNode;

This places the course struct in the same memory buffer as the course name. 这会将课程结构放置在与课程名称相同的内存缓冲区中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM