c语言 简单题 关于函数问题 200分 先谢谢各位高手

来源:百度知道 编辑:UC知道 时间:2024/06/30 14:08:02
#include "stdio.h"
struct Node{
int data;
struct Node *next;
};
struct Node *createNode()
{struct Node *tem;
if((tem=(struct Node*)malloc(sizeof(struct Node)))==NULL)
{printf("error");
exit(1);
}
else{
tem->data=NULL;
}
return tem;
}
void createLine(struct Node *rear,int item)
{struct Node *tem;
if((tem=(struct Node*)malloc(sizeof(struct Node)))==NULL)
{printf("error");
exit(1);
}
tem->data=item;
printf("tem_addr=%x,tem_value=%d\n",tem,tem->data);
rear->next=tem;
rear=tem;
printf("rear_add=%x,rear_value=%d\n",rear,rear->data);
}
main()
{struct Node *Node;
Node=createNode();
printf("1.-->%d\n2.-->%x\n3.-->%x\n",Node->data,Node->data,Node);
createLine(Node,2);
printf("after createLine:&#

第三次答复:
void createLine(struct Node *&rear,int item)

void createLine(struct Node **rear,int item)
实际上本质是一样的,你理解引用就可以了,不过这个改法挺巧妙,只要改一个字符,比我的好。

类似于函数int add(int &a)
int b;
add(b);
你在add函数里面是可以改函数外变量b的值一样。

你的函数加了&,这样就可以在createline函数里改函数外变量node的值了。

*******************************************
第二次答复:

我是一楼

输出是:
1.-->0
2.-->0
3.-->3d2470
tem_addr=3d24d8,tem_value=2
rear_add=3d24d8,rear_value=2
after createLine:

1.-->2
2.-->2
3.-->3d24d8
完全符合楼主的要求。

刚才有事走了,没解释一下,现在解释一下。
void createLine(struct Node *rear,int item)
这样子声明函数,你在函数里面只能改rear指针对应的对象值,而rear本身的值就是传入的node的值你是改不了的,
所以函数里面的
rear=tem;
你知识改变了函数局部变量rear值,但改不了传入的node的值。

所以得用指针的指针就可以改传入的node的值了。
传入的是node的地址,所以就可以根据node的地址改node的值了,当然也可以根据node的值改node对应的对象的值
(*rear)->next=tem;
就如我改的程序一样。

好像ywsbbdf -