Chinaunix

标题: 探討一個令人費解的小程序 [打印本页]

作者: shock_bn    时间: 2005-12-27 11:30
标题: 探討一個令人費解的小程序
下面一個小程序是我編寫的程序中抽取出來的,我覺得能夠通過,但結果卻segmentation fault, 鏈表創建函數的返回值如果改成指針型的LNode*,可以輸出預期結果,但如果void型就不行。但我覺得參數裏已經傳了可以在參數中自動返回回去的,望大家指教下面程序爲什麽會段錯誤?
#include <stdio.h>
#include <stdlib.h>

typedef struct LNode
{
        int iData;
        struct LNode *pNext;
} LNode;

void CreateLink(LNode *L, int iCount)
{
        int iNum;
        LNode *pointer = NULL;
        LNode *pNew = NULL;
        L = (LNode*)malloc(sizeof(LNode));
        L -> pNext = NULL;
        pointer = L;
        printf("The create serial is:\n");
        for (iNum = 0; iNum < iCount; ++iNum)
        {
                pNew = (LNode *)malloc(sizeof(LNode));
                if (NULL == pNew)
                {
                        printf("Cannot distribute enough room!\n");
                        return ;
                }
                scanf("%d", &pNew->iData);
                pNew->pNext = NULL;
                pointer->pNext = pNew;
                pointer = pNew;
                pNew = NULL;
        }
       
        return ;
}

int main(void)
{
        LNode *L = NULL;
        LNode *pointer = NULL;
        int iNum;
        printf("How many nodes you want to create?\n");
        scanf("%d",&iNum);
        CreateLink(L, iNum);
        pointer = L;
        printf("The serial of LinkList has been created is:\n");
        while (NULL != pointer->pNext)
        {
                pointer = pointer->pNext;
                printf("%d\n", pointer->iData);
        }
       
        return 0;
}
作者: shock_bn    时间: 2005-12-27 13:20
标题: 謝謝觀賞,問題已解決
不好意思,我應該在main函數中初始化L,否則會找不到L,解決方法如下:
L = (LNode*)malloc(sizeof(LNode)); 在創建函數中注掉,而在主函數中把原來的LNode *pointer = NULL; 改爲LNode *pointer = (LNode*)malloc(sizeof(LNode));
作者: sakulagi    时间: 2005-12-27 13:22
鼓励共享自己的发现。谢谢楼主
作者: shock_bn    时间: 2005-12-27 15:52
标题: 也可用指針的指針
當然如果在主函數調用時使用CreatList(&L, iNum);也可以,創建函數則變爲:
void CreateLink(LNode **L, int iCount)
{
        int iNum;
        LNode *pointer = NULL;
        LNode *pNew = NULL;
        *L = (LNode*)malloc(sizeof(LNode));
        (*L) -> pNext = NULL;
        pointer = (*L);
        printf("The create serial is:\n");
        for (iNum = 0; iNum < iCount; ++iNum)
        {
                pNew = (LNode *)malloc(sizeof(LNode));
                if (NULL == pNew)
                {
                        printf("Cannot distribute enough room!\n");
                        return ;
                }
                scanf("%d", &pNew->iData);
                pNew->pNext = NULL;
                pointer->pNext = pNew;
                pointer = pNew;
                pNew = NULL;
        }
        
        return ;
}




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2