首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

C++链表初始化失败,该如何处理

2013-07-01 
C++链表初始化失败#includestdio.h#includestdlib.h#includemalloc.h typedef struct LNode{int dat

C++链表初始化失败


#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
 typedef struct LNode{
int data;
struct LNode*next;
}LinkList;
typedef struct LNode LinkList;

void InitLinkList(LinkList *head)
{
(head)=(LinkList*)malloc(sizeof(LNode));
(head)->next=NULL;
(head)->data=0;
}
void Insert(LinkList *head,int data)
{
printf("开始建立节点:\n");
LNode*node=(LNode*)malloc(sizeof(LNode));
node->data=data;
node->next=NULL;
/*开始插入节点*/
printf("开始插入节点:\n");
LNode *p=head;
while(head->next!=NULL)
p=p->next;
p->next=node;
printf("插入节点完毕:");
}
int main()
{
LinkList *head=NULL;
InitLinkList(head);
for(int i=0;i<3;i++)
Insert(head,i);
}

我在InitLinklist函数中已经初始化了
head,但是在插入节点的时候,进入到了Insert函数后,head的data /next依然
是未定义的,没有初始化成功!
有些不解!
调试信息如下:

+head0x002b1540 {data=0 next=0x00000000 }LNode *
但是到了Insert函数执行时

+head0x002b14f8 {data=-842150451 next=0xcdcdcdcd }LNode *
就变成了这样
[解决办法]
void InitLinkList(LinkList *head)
这种参数只能改变 head 所指向的内容, 并不能改变 head 本身指向哪里. 你需要使用
void InitLinkList(LinkList**head) 才行.
[解决办法]

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
 typedef struct LNode{
int data;
struct LNode*next;
}LinkList;
typedef struct LNode LinkList;

void InitLinkList(LinkList **head)//这里改为LinkList**。。否则改变的只是head的副本。。不是head本身。。
{
(*head)=(LinkList*)malloc(sizeof(LNode));
(*head)->next=NULL;
(*head)->data=0;
}
void Insert(LinkList *head,int data)
{
printf("开始建立节点:\n");
LNode*node=(LNode*)malloc(sizeof(LNode));
node->data=data;
node->next=NULL;
/*开始插入节点*/
printf("开始插入节点:\n");
LNode *p=head;
while(p->next!=NULL)//这里是p->next不是head->next。。
p=p->next;
p->next=node;
printf("插入节点完毕:");
}
int main()
{
LinkList *head=NULL;
InitLinkList(&head);
for(int i=0;i<3;i++)
Insert(head,i);
}

[解决办法]
这个和 void f(int x); 里不能改变 x 的值是一样的.
你加一个 
typedef  LinkList* LinkListPtr;
然后你的函数定义就是 void InitLinkList(LinkListPtr head), 和 f 类似, 你不能改变 head 的值. 只能改变 head 指向的 LinkList 结构.

总之, 在函数参数里, 如果不是引用的话, 只有通过 (*xxx), xxx-> 方式改变的内容才会返回回去. 直接通过 xxx,  xxx. 操作的内容是不会返回的. 

热点排行