为什么以下temp和stNode显示不同的值?

时间:2015-10-19 14:19:34

标签: c

请查看以下代码。我试图通过调用insertNode()来创建一个链表,但为什么stNode没有返回分配的temp节点,而temp返回的是相同的?

#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node* link;
};

struct node *insertNode(struct node*stNode,int data)
{
    struct node* temp;
    temp = (struct node*)malloc(sizeof(struct node));
    temp->data = data;
    temp->link = NULL;

    if(stNode)
    {
        stNode=temp;
    }
    printf("stNode->data in insertNode is %d\n",stNode->data);
    return temp;
}

int main()
{
    struct node * list1;
    struct node * temp;
    temp = insertNode(list1,5);
    printf("In main\n");
    printf("temp->data  = %d\t, temp->link  = %u\n",temp->data,temp->link);
    printf("list1->data = %d\t, list1->link = %u\n",list1->data,list1->link);
    return;
}

输出:

stNode->data in insertNode is 5
In main
temp->data  = 5 , temp->link  = 0
list1->data = 11865500  , list1->link = 10636298

以上输出显示temp和list1的不同。为什么会这样?

2 个答案:

答案 0 :(得分:0)

stNode只是一个局部变量,在退出insertNode时会消失。

要在list1函数中修改main,请使用指针。

#include<stdio.h>
#include<stdlib.h>
struct node{
    int data;
    struct node* link;
};

struct node *insertNode(struct node**stNode,int data)
{

    struct node* temp;
    temp = (struct node*)malloc(sizeof(struct node));
    temp->data = data;
    temp->link = NULL;

    if(stNode)
    {
        *stNode=temp;
    }
    printf("stNode->data in insertNode is %d\n",(*stNode)->data);
    return temp;

}

int main(void)
{
    struct node * list1;
    struct node * temp;
    temp = insertNode(&list1,5);
    printf("In main\n");
    printf("temp->data  = %d\t, temp->link  = %p\n",temp->data,(void*)temp->link);
    printf("list1->data = %d\t, list1->link = %p\n",list1->data,(void*)list1->link);
    return 0;
}

答案 1 :(得分:0)

您实际上修改了参数值。正确的方法是:

    struct node *insertNode(struct node** stNode,int data)
    {
    ...
       if(stNode)
       {
           *stNode=temp;
       }
    ...
    }

    main()
    {
        ...
        temp = insertNode(&list1,5);

    }