2011-11-30 69 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

的一个问题是,你不使用它的价值