c - 使用二级指针初始化 SequenceList

标签 c list function pointers memory-management

我想使用二级指针来初始化序列表,它指向我为序列表创建的结构。我试过了,脚本可以编译成可执行文件,但是无法运行。

我使用 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/

相关文章:

ios - Swift 2 发布和响应代码转换有用的功能

c - Arduino 上使用 SPI 位联动的多个模数转换器

c - 魔术位板移动生成系统最实用的板表示是什么?

python-3.x - 如何编写一个函数,在不使用 return 的情况下更改原始整数列表?

list - 如何在 Scala 中复制列表

C++程序在函数调用处停止

python - python字典中的函数

C语言的手机账单计算器

c - Ubuntu-Daemon 不创建文件

python - 如何根据 Python 中另一个列表的(子列表)索引对列表进行分区