简体   繁体   中英

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. 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.
  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. Directly initialize them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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