1613551 发表于 2022-6-22 15:31:16

为什么传过去的要是指针本身的地址呢?

本帖最后由 1613551 于 2022-6-22 15:31 编辑

这个程序要实现的功能是,比如2和4之间插入一个3
为什么第61行是要取head头指针的地址呢?
后面赋值的时候,比如第14行然后又对head进行解引用赋值给current,那直接传入head不行吗?


#include <stdio.h>
#include <stdlib.h>
struct Node
{

    int value;
    struct Node *next;
};
void insertNode(struct Node **head, int value)
{
    struct Node *previous;
    struct Node *current;
    struct Node *new1;
    current = *head;
    previous = NULL;
    while (current != NULL && current->value < value)
    {
      previous = current;
      current = current->next;
    }
    new1 = (struct Node *)malloc(sizeof(struct Node));
    if (new1 == NULL)
    {
      printf("内存分配失败");
      exit(1);
    }
    new1->value = value;
    new1->next = current;
    if (previous == NULL)
    {
      *head = new1;
    }
    else
    {
      previous->next = new1;
    }
}
void printNode(struct Node *head)
{
    struct Node *current;
    current = head;
    while (current != NULL)
    {
      printf("%d ", current->value);
      current = current->next;
    }
    putchar('\n');
}
int main(void)
{
    struct Node *head = NULL;
    int input;
    while (1)
    {
      printf("请输入一个整数(输入-1表示结束):");
      scanf("%d", &input);
      if (input == -1)
      {
            break;
      }
      insertNode(&head, input);
      printNode(head);
    }
}

风车呼呼呼 发表于 2022-6-22 15:45:24

形参head是指向节点指针的指针,current和head是节点指针

1613551 发表于 2022-6-22 15:55:32

风车呼呼呼 发表于 2022-6-22 15:45
形参head是指向节点指针的指针,current和head是节点指针

为什么要传指向节点的指针过去,而不能传节点指针,后面赋值的时候也是对指向节点的指针进行解引用把节点指针赋值过去的

jhq999 发表于 2022-6-22 16:05:35

1613551 发表于 2022-6-22 15:55
为什么要传指向节点的指针过去,而不能传节点指针,后面赋值的时候也是对指向节点的指针进行解引用把节 ...

实参不随形参改变而改变,所以只能把可能会改变的变量把它的指针传入函数,这样才能在子函数里改变主函数里的变量。
注意 指针也是变量

1613551 发表于 2022-6-22 16:23:06

jhq999 发表于 2022-6-22 16:05
实参不随形参改变而改变,所以只能把可能会改变的变量把它的指针传入函数,这样才能在子函数里改变主函数 ...

懂了

风车呼呼呼 发表于 2022-6-22 16:24:31

1613551 发表于 2022-6-22 15:55
为什么要传指向节点的指针过去,而不能传节点指针,后面赋值的时候也是对指向节点的指针进行解引用把节 ...

期望达到的效果是主函数中的变量head能改变。形参接收的是变量值的一份拷贝,传head在函数里面往后接入再多节点,也和主函数的head没关系。
页: [1]
查看完整版本: 为什么传过去的要是指针本身的地址呢?