繁体   English   中英

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

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

创建链接列表节点时,我很难使用malloc动态分配内存。

对于我的作业,我们必须使用以下结构定义:

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

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

CourseList结构是实际的链接列表节点,而Course结构包含Course名称和已注册学生的二进制搜索树。 您会注意到struct Course在struct CourseList内部。

我需要创建一个新的CourseList节点,并给定一个字符串用作内部Course结构的name字段,并使用基于字符串长度的动态分配。 我已经尝试过根据字符串的长度来分配外部结构和内部结构的所有组合,但是我似乎无法正确地将name字符串复制到内部结构中。 我敢肯定有一个简单的答案,但是我找不到。

我已经尝试过根据字符串的长度来分配外部结构和内部结构的所有组合,但是我似乎无法正确地将名称字符串复制到内部结构中。

这是因为字符串的长度不会更改分配具有固定大小的struct的方式。 字符串需要单独分配,并分配给CourseList data成员的name成员:

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

注意newNode前面的星号。 这是因为CourseList是指针类型。

好吧,如果您真的想根据字符串长度来分配结构:

  /* 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;

这会将课程结构放置在与课程名称相同的内存缓冲区中。

暂无
暂无

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

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