繁体   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