我想使用二级指针来初始化序列表,它指向我为序列表创建的结构。我试过了,脚本可以编译成可执行文件,但是无法运行。
我使用 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)=(LinkList)malloc(sizeof(struct LNode));
(*L)->data= 0;
现在你去做:
Sqlist La;
InitList(&La);
这将执行:
int InitList(Sqlist *L) {
(*L)->elem=(ElemType*)malloc(sizeof(ElemType)*LISTSIZE);
但是指针没有内存!它指向哪里?没有人确切知道。您取消引用指针,请求它的成员 elem
,然后砰!你刚刚调用了未定义的行为,这是肯定的!
the code compiles but fails to operate.
这就是你的程序“无法运行”的方式,因为你有逻辑错误,如上所述。
您首先需要为 Sqlist
分配内存,就像之前为 LinkList
所做的那样,然后访问其成员。
PS:将指针初始化为 NULL 是一种很好的做法,如下所示:Sqlist La = NULL;
。
哦,顺便说一下,与您的问题无关,Do I cast the result of malloc?不!
关于c - 使用二级指针初始化 SequenceList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46256837/