简体   繁体   中英

Setting a pointer to struct to equal to another pointer to struct returned by a function?

I'm trying to build a linked list but for some reason my head is not updated properly. Here are the snippets of my code that are not working as I intended:

typedef struct node {
  int data;
  struct node *next;
} * node;

node create_node(int data) {
  node to_return = calloc(1, sizeof(struct node));
  to_return->data = data;
  to_return->next = NULL;
  return to_return;
}

int insert(int data, node head) {
  if (head == NULL) {
    head = create_node(data);
  }
  .
  .
  .
  }
  return 1;
}

int main(int argc, char **argv) {

  node head = NULL;
  insert(1, head);

  printf("head->data: %d", head->data);
}

In this example, I'm trying to create the first node of the linked list using insert(). However, I'm getting a SEG fault, which means that the to_return node pointer returned by create_node() is not being set to the node head in insert() properly. What am I missing here?

EDIT: I double checked and head is getting set properly in insert(). The changes just don't persist for some reason

Pass a pointer to the node:

int insert(int data, node* head) {
  if (*head == NULL) {
    *head = create_node(data);
  }
  .
  .
  .
  }
  return 1;
}

int main(int argc, char **argv) {

  node head = NULL;
  insert(1, &head);

  printf("head->data: %d", head->data);
}

(and btw that typedef is really confusing, since the insert function's second parameter is actually of type struct node ** )

In C and C++ all function parameters are passed by value, unless explicitly marked as by reference. This includes pointer parameters.

Your insert function is attempting to change the first parameter if the case that it is a null pointer. This will not work, as any changes made to the pointer will not pass from the function. You need to either pass a node *head or a node& head (in C++) to your insert function if you want to be ab le to change head .

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