簡體   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