Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

C语言单链表初始化问题

clipboard.png
上图为debuger截图
下面是相关代码:

typedef struct Node
{
    ElementType Element;
    Position    Next;
} Node;

typedef struct Node *PtrToNode;
typedef PtrToNode List;

void InitList( List *L)
{
    (*L) = (Node *)malloc(sizeof(Node));        //这一行会有错误
    if((*L) == NULL)
    {
        printf("
 Failed to malloc memory to init List!
");
        exit(1);
    }
    (*L)->Next = NULL;
}
int main()
{
    List *L;
    InitList(L);
}

我想问的是问题出在哪里,我Google也找了Signal=SIGSEGV(Segmentation fault),还是没找到问题出在哪里。望指教!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

首先按照你的逻辑来改

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

typedef struct Node
{
    // ElementType Element;
    // Position    Next;
    int elem; //初始化不涉及节点内容,随便写一个
    struct Node* next;
} Node;

typedef Node *PtrToNode;
typedef PtrToNode List;

void InitList(List *L)
{
    (*L) = (Node *) malloc(sizeof(Node));
    if((*L) == NULL)
    {
        printf("
 Failed to malloc memory to init List!
");
        exit(1);
    }
    (*L)->elem = 0;
    (*L)->next = NULL;
    printf("malloc done.
");
}
int main()
{
    List L;
    InitList(&L);//这里改了
    printf("L->elem=%d
", L->elem);
}

其次关于init, 你看这要写会不会更容易理解些, 也更有初始化内存并分配的味道

List InitList()
{
    List L = (Node *) malloc(sizeof(Node));
    if(L == NULL)
    {
        printf("
 Failed to malloc memory to init List!
");
        exit(1);
    }
    L->elem = 0;
    L->next = NULL;
    printf("malloc done.
");

    return L;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...