函数传递指针的问题

来源:百度知道 编辑:UC知道 时间:2024/07/07 06:51:24
#include <stdlib.h>
#include <stdio.h>

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

int InitList_L(struct LNode * l){
l = (LNode *)calloc(1, sizeof(LNode));
l->data = 0;
l->next = NULL;
return 0;
}

int main(){
struct LNode l;

InitList_L(&l);
printf("%d\n", l.data);
return 0;
}

这样一段函数,为什么运行出来的结果是-858993460?
在InitList_L里不是已经为data域赋值过了吗??

我觉得是这样的:
InitList_L(&l); 这一句的确把l的引用传进InitList_L函数里了,但是注意InitList_L函数的第一句语句:
l = (LNode *)calloc(1, sizeof(LNode)); 即用calloc分配内存,而事实上main函数中struct LNode l; 声明的同时已经为其分配内存了,只是没有初始化,现在又用calloc为其分配,其实使得在InitList_L中的l指向一个新的LNode结点l',修改了函数中l的指针,这样你对l'的data赋值,退出函数后再print l的data,应该还是没有初始化的。
总而言之,关键就在那句l = (LNode *)calloc(1, sizeof(LNode));你如果把它注释掉,结果肯定就是你希望的0了。
希望这个回答你能满意。

因为你定义的l是stuct LNode类的普通变量,在调用函数InitList_L(&l)时,进行的是值传递,进行的运算是传递不回来的,而你在定义时没有给l赋初值,运行出来就是初始的垃圾值啦,这也就是为什么我们有时候要用指针进行参数传递了。

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

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

int InitList_L(struct LNode * l){
//l = (LNode *)calloc(1, sizeof(LNode));
//上句去掉
l->data = 0;
l->next = NULL;
return 0;
}

int main(){
struct LNode l;

InitList_L(&l);
printf("%d\n", l.data);
return 0;
}
这位仁兄大概是脑子一