簡體   English   中英

C 編程為鏈表類型結構分配空間

[英]C programming allocating space for a linked list type structure

嗨,我剛開始嘗試在 C 中實現某種列表的東西,只是為了嘗試更好地學習。 我目前沒有代碼,只需要一些假設的幫助

#define MAX_LIST_SIZE 1024


typedef struct clist clist;

struct clist{
   
   clist *next;
   char  *data; 
 
}

void add_to_list(char *str, clist *current){
   //what code goes in here
   im guessing some sort of malloc adding the strlen of str plus the sizeof the clist
}

int main(){
   clist mylistofstrings;
}

如果你能回答這個問題,我的下一個問題是,有沒有辦法使用宏或其他東西來改變結構,這樣你就可以添加如下字符串

clist mystrings = ADDSTRING("add this");
ADDTOLIST(mystrings,"second string");

有趣的是,您必須注意以下幾點:

如果您要傳遞對鏈接列表的引用:

  1. 您需要首先為堆中的每個節點分配結構。 避免堆棧粉碎。
  2. 您甚至可能不得不 malloc 您的字符串,再次避免堆棧粉碎。
  3. 然后,您必須將每個節點相互鏈接。

如果您只是為了好玩而這樣做,並且您不打算將對您的結構的引用傳遞給不同的函數。 那么你就不需要使用malloc了。 直接初始化它們。

暫無
暫無

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

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