Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to use malloc to insert a node in a linked list?
    text
    copied!<p>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!</p> <p>Thanks!</p> <p>Here's main.c:</p> <pre><code>#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", &amp;(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; } </code></pre> <p>Here's InNode.c (directly from my book):</p> <pre><code>#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-&gt;data = item; printf("start if statement.\n"); if (pPre == NULL) { pNew-&gt;link = pList; pList = pNew; } else { pNew-&gt;link = pPre-&gt;link; pPre-&gt;link = pNew; } printf("end else statement.\n"); return pList; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload