【发布时间】:2018-02-25 15:57:57
【问题描述】:
我想通过使用第二个等级指针来初始化序列列表,它指向我为序列列表创建的 STRUCT。我试过了,脚本可以编译成可执行文件,但是不能运行。
我使用 C 和 DEV CPP 5.11 作为 IDE。
我只想使用 *Sqlist 作为我的参数来初始化一个序列列表...
这是序列表。
/* can be compiled ,but fail to execute.*/
#include <stdio.h>
#include <stdlib.h>
#define LISTSIZE 10
typedef int ElemType;
typedef struct List{
ElemType *elem;
int length;
int listsize;
}List,*Sqlist;
int InitList(Sqlist *L){
(*L)->elem=(ElemType*)malloc(sizeof(ElemType)*LISTSIZE);
if (!(*L)->elem) return -1;
(*L)->length=0;
(*L)->listsize=LISTSIZE;
}
int main(){
Sqlist La;
InitList(&La);
}
这与我使用第二级指针作为 Initialize 函数的参数创建的链接列表相比令人困惑。
#include <stdlib.h>
#include <stdio.h>
#include <typeinfo.h>
typedef int ElemType ;
typedef struct LNode{
ElemType data;
struct LNode* next;
}LNode,*LinkList;
int InitList(LinkList *L) {
(*L)=(LinkList)malloc(sizeof(struct LNode));
if (!*L) return -1;
(*L)->data= 0;
(*L)->next =NULL;
printf("successfully initialized.\n");
return 0;
}
非常感谢您的帮助!
【问题讨论】:
-
你没看出区别吗?在链表中,您为节点本身分配空间,然后填充它。在您的序列列表中,您分配给
(*L)->elem,尽管*L尚不存在。 -
(我发现为空列表分配虚拟节点的做法也有问题。链表是没有节点的列表,可以在定义时初始化:
List *La = NULL;)
标签: c list function pointers memory-management