首页 > 解决方案 > 为什么我的函数使用按值调用方法?

问题描述

我不知道为什么在最后一行打印第一个元素的数据而不是最后一个元素。我要解释。

// A simple C program for traversal of a linked list 
#include <stdio.h> 
#include <stdlib.h> 

struct Node { 
    int data; 
    struct Node* next; 
}; 

// This function prints contents of linked list starting from 
// the given node 
void printList(struct Node* n) 
{ 
    while (n != NULL) { 
        printf(" %d ", n->data); 
        n = n->next; 
    } 
} 

int main() 
{ 
    struct Node* head = NULL; 
    struct Node* second = NULL; 
    struct Node* third = NULL; 

    // allocate 3 nodes in the heap 
    head = (struct Node*)malloc(sizeof(struct Node)); 
    second = (struct Node*)malloc(sizeof(struct Node)); 
    third = (struct Node*)malloc(sizeof(struct Node)); 

    head->data = 1; // assign data in first node 
    head->next = second; // Link first node with second 

    second->data = 2; // assign data to second node 
    second->next = third; 

    third->data = 3; // assign data to third node 
    third->next = NULL; 

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

    return 0; 
}

由于该函数正在接受指针,因此应该通过引用调用它。当 n 指针等于 NULL 时,在函数的最后一个循环中。但是在这段代码的最后一行是打印我的链表的第一个列表的数据。

标签: pointers

解决方案


实际上你正在做的事情并没有在实际的链表中完成,它不是通过引用传递的

void printList(struct Node* n) 
{ 
   /* some code here */
} 

void main()
{
    /* all your code here */
    printList(head);
}    

因此,如果您想更改实际链表中的头,则必须将指针头的地址传递给类似这样的函数

int append_list(node **head, int data)
{
    while((*head)->next!=NULL)
    {
        (*head) = (*head)->next;
    }
}



int main()
{
    struct node *head = NULL;
 
    /* add nodes */

    print_list(&head);

}

所以这是您的代码中的修改:

   #include <stdio.h> 
   #include <stdlib.h> 

   struct Node { 
     int data; 
     struct Node* next; 
   }; 

   // This function prints contents of linked list starting from 
   // the given node 
   void printList(struct Node** n) 
   { 
        while ((*n)->next != NULL) { 
        printf(" %d ", (*n)->data); 
        (*n) = (*n)->next; 
   } 
} 

int main() 
{ 
   struct Node* head = NULL; 
   struct Node* second = NULL; 
   struct Node* third = NULL; 

   // allocate 3 nodes in the heap 
   head = (struct Node*)malloc(sizeof(struct Node)); 
   second = (struct Node*)malloc(sizeof(struct Node)); 
   third = (struct Node*)malloc(sizeof(struct Node)); 

   head->data = 1; // assign data in first node 
   head->next = second; // Link first node with second 

   second->data = 2; // assign data to second node 
   second->next = third; 

   third->data = 3; // assign data to third node 
   third->next = NULL; 

   printList(&head); 

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

   return 0; 
}

这里的输出将是

  1 2 3

由于您已使用 (*head) 进行遍历,因此您不再有权访问您的列表,因此如果您尝试访问,则会出现分段错误

 (*head)->next

但我不建议这样做,因为现在您将无法释放内存


推荐阅读