Home » c# » c – Assign only one node of a struct to the same type of struct

c – Assign only one node of a struct to the same type of struct

Posted by: admin February 21, 2020 Leave a comment

Questions:

Good day. I have a struct list, with the elements “name, available and *next”. In the code below I am trying to get only one node (resource) into a list of the same struct. If I do this with the provided code, all the elements after that node (because of *next) are also put into the new list. Is there a way to take only the one node and put it into the new list?

struct resourceList *list = p->resourceListPtr;
    if (list == NULL) {
      list = resource;
      list->next = NULL;
      p->resourceListPtr = list;
}

The list->next = NULL, changes the resource->next to NULL as well. But how can I only change it for the second list?

How to&Answers:

If you want to copy a node, you have to copy the memory used by it, into newly allocated memory.

Something like:

if (list == NULL)
{
  list = malloc(sizeof *list);
  if (list != NULL)
  {
    *list = *resource;
    list->next = NULL;
    p->resourceListPtr = list;
  }
}

###

Short answer is: You can’t.

If you want a “node” to be a member of two different lists, you have to design the list and node structures with that in mind from the beginning (for example by having separate structures for the data and the actual list nodes).

What you might be able to do is to copy the node from the existing list to the new list. That means you have to create a brand new struct resourceList node, copy it from resource and then add the new node to the list.

Perhaps something like

if (list == NULL)
{
    // Create a new node
    list = malloc(struct resourceList);

    // Copy the data from another node
    *list = *resource;

    // No nodes after this one
    list->next = NULL;

    // Make the new node the head of the list
    p->resourceListPtr = list;
}

[Error checking omitted]