【问题标题】:Linked list, doesnt work when passing head of the list as argument in function链表,将列表的头部作为函数中的参数传递时不起作用
【发布时间】:2016-02-15 20:53:57
【问题描述】:

在函数中将列表头作为参数传递时会出现什么问题?

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

typedef struct node
{
    int value;
    struct node* next;

}node;
node* h1 = NULL;

void ubaci(int x, node *head)
{
    node *novi = (node*)malloc(sizeof(node));
    novi->value = x;
    novi->next = head;
    head = novi;
}

void ispisi(node *head)
{
    node *temp = head;

    while(temp != NULL)
    {
        printf("%d -> ",temp->value);
        temp = temp->next;
    }
}

int main()
{
    int x = 0;

    while(x<10)
    {
        x++;
        ubaci(x,h1);
    }
    ispisi(h1);

    return 0;
}

这不起作用,我不知道为什么。但是当我尝试使用这些函数而不将列表的头部作为参数传递并使用全局变量时,它可以完美地工作。 示例:

void ubaci(int x)
{
    node *novi = (node*)malloc(sizeof(node));
    novi->value = x;
    novi->next = h1;
    h1 = novi;
}

void ispisi()
{
    node *temp = h1;

    while(temp != NULL)
    {
        printf("%d -> ",temp->value);
        temp = temp->next;
    }
}

【问题讨论】:

标签: c list pointers linked-list singly-linked-list


【解决方案1】:

函数参数是它的局部变量。局部变量的任何更改都不会影响原始参数。

如果你想在函数中改变参数,你应该通过引用传递参数。

例如

void ubaci(int x, node **head)
{
    node *novi = (node*)malloc(sizeof(node));
    novi->value = x;
    novi->next = *head;
    *head = novi;
}

函数调用可能看起来像

ubaci( x, &h1 );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-07
    • 1970-01-01
    相关资源
    最近更新 更多