I’m writing a program that calls a function in main that creates a node to build a linked list. The program reads characters from a file to be placed in the nodes. The program runs fine until it gets into the function creating the nodes. I’m not sure if there is a logical or syntactical error or something else. Sorry for the length, but the errors aren’t far from the beginning. Also, let me know if you want my header file. The code is from my C book: Computer Science: A Structured Programming Approach Using C, Third Edition. Any help (and explaination of my errors) would be greatly appreciated!
Thanks!
Here’s 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;
}
Here’s InNode.c (directly from my book):
#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;
}
One problem that I notice immediately:
You have an if statement, with no braces around the body, and two lines indented as if they are supposed to be within the body of the if statement. Only the first line is being parsed as being part of the if statement; the second line, the
exit(100), is happening unconditionally, so your program is exiting no matter what.You should probably change this to:
If that doesn’t solve your problem, or in general for future questions, I would suggest you post the output that you get. It can be a lot easier for people to find problems if you post detailed information about what actually happens (such as the output, the unexpected behavior and what you expected, or the like), rather than just saying that it doesn’t work with no more detail.