简体   繁体   English

C 编程为链表类型结构分配空间

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

Hi i am at the beginning of trying to implement some kind of list thing in C just to try and learn a little better.嗨,我刚开始尝试在 C 中实现某种列表的东西,只是为了尝试更好地学习。 I have no code currently, just need some help with a hypothetical我目前没有代码,只需要一些假设的帮助

#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;
}

if you can answer that, my next question is, is there a way of changing the structure using a macro or something so you can add strings like the following如果你能回答这个问题,我的下一个问题是,有没有办法使用宏或其他东西来改变结构,这样你就可以添加如下字符串

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

Interesting, you will have to note some points though:有趣的是,您必须注意以下几点:

If you are going to pass references to your linked list around:如果您要传递对链接列表的引用:

  1. You will need to allocate the structure for each node in the heap first.您需要首先为堆中的每个节点分配结构。 To avoid stack smashing.避免堆栈粉碎。
  2. You might even have to malloc your string, again to avoid stack smashing.您甚至可能不得不 malloc 您的字符串,再次避免堆栈粉碎。
  3. Then, you will have to link each node to each other.然后,您必须将每个节点相互链接。

If you are just doing it for fun, and you are not planning to pass references to your structure to different functions.如果您只是为了好玩而这样做,并且您不打算将对您的结构的引用传递给不同的函数。 Then you don't need to use malloc.那么你就不需要使用malloc了。 Directly initialize them.直接初始化它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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