簡體   English   中英

在另一個結構中分配 struct 的內存

[英]allocate memory of struct within another structure

我正在實施 BST,需要您的建議。 代碼有2個結構。 我需要在項目結構中分配鏈接結構。 我該怎么做? 我需要同時分配item->link->left & item->link->right嗎? 請舉例說明?

struct link;
struct link
{
   struct link *left;
   struct link *right;
};

struct item
{
   struct link link;
   uint8_t c;
};

在某處插入函數

item *temp = NULL;

// 我將如何分配內存??

首先,您必須為item分配內存。

item *temp = NULL;
temp = malloc(sizeof(item)); // alocate memory for 1 item

擁有item后,您必須為左右鏈接分配內存

temp->link.left = malloc(sizeof(link));
temp->link.left = malloc(sizeof(link));

請注意. ,它在那里是因為來自itemlink不是指針。

列表結構是堆棧結構內的一個成員。 堆棧封裝了列表。 這是一種使用幾個函數進行 malloc 和初始化場景的方法。 希望能幫助到你!

typedef struct currentPos{
   int x;
   int y;
   currentPos * next;
}currentPos;

typedef struct stack
{
     currentPos * list;
}stack;

int main(){
     stack * myStack;
     myStack = malloc(sizeof(stack)*1);  // mallocing shell
     myStack = createStack(myStack);
     return(0);
 }

 stack * createStack(stack * myStack)
 { 
     myStack->list = createList();
     return(mtStack);
 }

 currentPos * createList()
 {
     currentPos * theHead;
     theHead = malloc(sizeof(currentPos)*1);   // mallocing inside
     theHead->x= 0;
     theHead->y=0;
     theHead->next = NULL
     return(theHead);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM