简体   繁体   中英

Problems with a Linked List in C

I'm making a linked list (of structs) in C, but I want to be able to call a function and have it add 4-5 stucts to the list by itself. The problem is since in C all the variables created in functions are left on the stack/heap I have no clue how I am supposed to accomplish this.

Here is a code example:

struct listItem
{
   int value;
   listItem *left;
   listItem *right;
}

void addItems(listItem *l)
{
   listItem one, two, three;
   l->left = &one;
   one.left = &two;
   two.left = &three;
}

int main (char *a [])
{
   listItem l;
   addItems(l);
}

Obviously this will not work. How might I accomplish this? Is it even possible. Thanks

EDIT: Wow thank you everyone for the help. That was faster and more helpful than I could have imagined!

You have to allocate your "one", "two", "three" with malloc() instead of creating them on the stack. After you're done with them, you'll have to walk through the list again and call free () on the memory so that your program doesn't leak.

Try this addItem instead...

void addItem(listItem *l, int value)
{
   listItem* item = malloc (sizeof (listItem));
   item->value = value;
   item->next = 0;
   item->prev = l; // Probably not what you want, but you were only singly linking in the example

   l->next = item;
}

In this code:

void addItems(listItem *l)
{
   listItem one, two, three;
   l->left = &one;
   one.left = &two;
   two.left = &three;
}

All of the variables are left on the stack, not the heap. Probably you want to allocate them on the heap, so that you can refer a pointer to them that will not be invalid once the stack frame is left:

void addItems(listItem *l)
{
   listItem *one=calloc(1, sizeof(*one)), 
     two=calloc(1, sizeof(*two)),
     three=calloc(1, sizeof(*three));
   l->left = one;
   one.left = two;
   two.left = three;
}

addItems() has to allocate memory:

void addItems(listItem *l)
{
   listItem* one = (listItem*)malloc(sizeof(listItem));
   listItem* two = (listItem*)malloc(sizeof(listItem));
   listItem* three = (listItem*)malloc(sizeof(listItem));
   l->left = 0;
   l->right = one;
   one->left = l;
   one->right = two;
   two->left = one;
   two->right = three;
   three->left = two;
   three->right = 0;
}

int main ()
{
   listItem l;
   addItems(&l);
}

I'm assuming you are out to create a double linked list, so I liberty in setting the left/right pointers accordingly. If I'm wrong in my assumption, please adjust so it suits your needs.

Cheers

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