我正在写一个程序,调用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;
}
谢谢,这工作(如WEEL为initializig PPRE)之前初始化
pPre
。对不起,关于输出。我会在下一次做笔记! – Piseagan@Piseagan很高兴能帮到你!是的,初始化pPre也很重要。我也刚刚注意到你已经发表了评论,说明它停止了工作,但是我没有看到那个评论,因为它太偏离了右边。所以,你确实发布了我正在寻找的信息(它死的地方),但格式可能会更好。 –