My goal with the following code was to have a user enter some integers, have those integers stored in stack allocated nodes of type INT_NODE and then link all those nodes together. Finally, I wanted to iterate through the list and print out the element at each node (only the first 5 in the following code). When I enter some numbers, however, the program prints out the first number I entered, and then the last number I entered repeated 4 times. For example, if I enter 84 5 12 7 1 22 31[Enter] and then press Ctrl+D at the beginning of the next line to simulate EOF on this Mac, I get the following output; 84 31 31 31 31. I can't figure out why it is doing this.
I am aware that I could allocate the nodes on the heap using malloc() and I have already written a function to do that. I was just wondering if it were possible to do it using the runtime stack.
In the following code, the INT_NODE type is defined in the "SortingAlgs.h" header as the following;
typedef struct INT_NODE {
int element;
struct INT_NODE *next;
} INT_NODE;
#include <stdio.h>
#include <stdlib.h>
#include "SortingAlgs.h"
int main(void) {
INT_NODE head = {-999999999};
int num;
INT_NODE *pCurrentNode = &head;
if (scanf("%d", &num) != EOF) {
head.element = num;
while (scanf("%d", &num) != EOF) {
INT_NODE newNode;
newNode.element = num;
newNode.next = NULL;
pCurrentNode->next = &newNode;
pCurrentNode = pCurrentNode->next;
}
}
int i;
for (pCurrentNode = &head, i = 0; i < 5;
pCurrentNode = pCurrentNode->next, i++)
printf("%d ", pCurrentNode->element);
printf("\n");
return 0;
}