Pis*_*gan 1 c malloc linked-list nodes
我正在编写一个程序,在main中调用一个函数来创建一个节点来构建一个链表.程序从要放置在节点中的文件中读取字符.程序运行正常,直到它进入创建节点的函数.我不确定是否存在逻辑或语法错误或其他错误.抱歉长度,但错误距离一开始并不远.另外,如果您需要我的头文件,请告诉我.代码来自我的C书:计算机科学:结构化编程方法使用C,第三版.任何帮助(并解释我的错误)将不胜感激!
谢谢!
这是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;
}
Run Code Online (Sandbox Code Playgroud)
这是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;
}
Run Code Online (Sandbox Code Playgroud)
我立即注意到的一个问题:
if (!(pNew = (NODE*) malloc(sizeof(NODE))))
printf("Memory overflow in insert.\n");
exit(100);
Run Code Online (Sandbox Code Playgroud)
你有一个if语句,身体周围没有括号,两行缩进,好像它们应该在if语句的主体内.只有第一行被解析为if语句的一部分; 第二行,exit(100)无条件发生,所以你的程序无论如何都会退出.
您应该将其更改为:
if (!(pNew = (NODE*) malloc(sizeof(NODE))))
{
printf("Memory overflow in insert.\n");
exit(100);
}
Run Code Online (Sandbox Code Playgroud)
如果这不能解决您的问题,或者通常会解决您未来的问题,我建议您发布您获得的输出.如果您发布有关实际发生的事件的详细信息(例如输出,意外行为和您期望的内容等),那么人们可以更容易地发现问题,而不仅仅是说它不起作用没有更多细节.