简体   繁体   中英

C: malloc for linked list node (struct within struct)

I'm having difficulties using malloc to dynamically allocate memory when creating linked list nodes.

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. You'll notice the struct Course is inside the 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. 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. 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. String needs to be allocated separately, and assigned to name member of data member of CourseList :

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

Note the asterisk in front of newNode . This is because CourseList is a pointer type.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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