2011-11-30 70 views
1

我正在寫一個程序,調用main中的一個函數來創建一個節點來構建一個鏈表。該程序從文件中讀取要放置在節點中的字符。程序運行良好,直到它進入創建節點的函數。我不確定是否存在邏輯或語法錯誤或其他問題。對不起,但錯誤離開頭不遠。另外,讓我知道你是否想要我的頭文件。代碼來自我的C書:計算機科學:一種使用C的結構化編程方法,第三版。任何幫助(和我的錯誤解釋)將不勝感激!如何使用malloc在鏈表中插入節點?

謝謝!

這裏的main.c:

#include "my.h" 

int main (int argc, char* argv[]) 
{ 
    int y; 
    NODE* pList; 
    NODE* pPre; 
    NODE* pNew; 
    DATA item; 
    FILE* fpntr; 
    int closeResult; 

    pList = NULL;   

    fpntr = fopen(argv[1], "r");       // open file 
     if(!fpntr) 
      { 
       printf("Could not open input file.\n"); 
       exit (101); 
      } 
     else printf("The file opened.\n"); 


printf("starting InNode.\n");         //testing to see if this is working 

    while((y = fscanf(fpntr, "%c", &(item.key))) != EOF) 
      pList = InNode(pList, pPre, item); 

printf("end InNode.\n");          //testing to see if this is working, doesn't get this far 

printf("starting printme.\n"); 


    printme(pList); 


printf("end printme.\n"); 

    closeResult = fclose(fpntr);        //close file 
     if(closeResult == EOF) 
      { 
       printf("Could not close input file.\n"); 
       exit (102); 
      } 
     else printf("The file closed.\n"); 

    free(a); 
    return 0; 
} 

這裏的InNode.c(直接從我的書):

#include "my.h" 

NODE* InNode (NODE* pList, NODE* pPre, DATA item) 

{ 
    NODE* pNew; 

printf("start malloc.\n");         //testing to see if this is working 

    if (!(pNew = (NODE*) malloc(sizeof(NODE)))) 
     printf("Memory overflow in insert.\n"); 
     exit(100); 


printf("malloc complete.\n");        //testing to see if this is working, doesn't get this far 


    pNew->data = item; 

printf("start if statement.\n"); 

    if (pPre == NULL) 
     { 
      pNew->link = pList; 
      pList = pNew; 
     } 
    else 
     { 
      pNew->link = pPre->link; 
      pPre->link = pNew; 
     } 

printf("end else statement.\n"); 

    return pList; 
} 

回答

5

的一個問題,我注意到立即:

if (!(pNew = (NODE*) malloc(sizeof(NODE)))) 
    printf("Memory overflow in insert.\n"); 
    exit(100); 

您有一條if語句,在body的周圍沒有大括號,並且兩行縮進,就好像它們應該在if語句的主體中一樣。只有第一行被解析爲if語句的一部分;第二行exit(100)無條件地發生,所以無論如何你的程序都在退出。

你或許應該將其更改爲:

if (!(pNew = (NODE*) malloc(sizeof(NODE)))) 
{ 
    printf("Memory overflow in insert.\n"); 
    exit(100); 
} 

如果不解決您的問題,或者一般的未來的問題,我建議你發佈你得到的輸出。如果你發佈關於實際發生的事情的詳細信息(例如輸出,意想不到的行爲以及你的期望等),那麼人們可以更容易地發現問題,而不僅僅是說它不起作用沒有更多的細節。

+0

謝謝,這工作(如WEEL爲initializig PPRE)之前初始化pPre。對不起,關於輸出。我會在下一次做筆記! – Piseagan

+0

@Piseagan很高興能幫到你!是的,初始化pPre也很重要。我也剛剛注意到你已經發表了評論,說明它停止了工作,但是我沒有看到那個評論,因爲它太偏離了右邊。所以,你確實發佈了我正在尋找的信息(它死的地方),但格式可能會更好。 –

3

你缺少{ }

if (!(pNew = (NODE*) malloc(sizeof(NODE)))) 
{ 
    printf("Memory overflow in insert.\n"); 
    exit(100); 
} 
1

的一個問題是,你不使用它的價值