繁体   English   中英

将指向结构的指针设置为等于函数返回的指向结构的另一个指针?

[英]Setting a pointer to struct to equal to another pointer to struct returned by a function?

我正在尝试建立一个链表,但由于某种原因,我的头未正确更新。 以下是我的代码片段无法正常工作:

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

在此示例中,我尝试使用insert()创建链接列表的第一个节点。 但是,我遇到了SEG错误,这意味着create_node()返回的to_return节点指针未正确设置为insert()中的节点头。 我在这里想念什么?

编辑:我仔细检查过,并正确地将头设置在insert()中。 由于某些原因,更改不会持久

将指针传递给节点:

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

(顺便说一下,typedef确实令人困惑,因为insert函数的第二个参数实际上是struct node **类型)

在C和C ++中,除非明确标记为引用,否则所有函数参数均按值传递。 这包括指针参数。

如果insert函数为空指针,则您的insert函数将尝试更改第一个参数。 这将不起作用,因为对指针所做的任何更改都不会从该函数传递。 如果您想更改head需要将node *headnode& head (在C ++中)传递给insert函数。

暂无
暂无

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

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