Can anyone help me with the below code?
I have got it running, but after starting the program it hangs after outputting 1,2,3,4.... instead of outputting then automatically exiting.
Code:
#include <stdio.h>
#include <stdlib.h>
/* Small program to explore using singly linked ring lists.
A ring list is one in which the last item in the list points
first item in the list rathern than NULL
*/
struct intRecord
{
int number;
struct intRecord *next;
};
typedef struct intRecord intNode;
void copyArrayToList(intNode **start, int array[], int size);
void printList(intNode *start);
void freeList(intNode **start);
intNode* newNode(int number);
int main()
{
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
intNode *start = NULL;
copyArrayToList(&start, array, 10);
printList(start);
freeList(&start);
return 0;
}
void copyArrayToList(intNode **start, int array[], int size)
{
/* Create a new linked ring list and copy the contents of
array into it
*/
int i;
intNode *temp;
for (i=0; i<size; i++)
{
temp = newNode(array[i]);
if (*start == NULL)
{
/* add 1st item to ring list */
*start = temp->next = temp;
}
else
{
/* add another item to ring list */
temp->next = (*start)->next;
(*start)->next = temp;
*start = temp;
}
}
/* make start point to the 1st item added to the ring list */
if (*start != NULL) *start = (*start)->next;
}
void printList(intNode *start)
{
/* Print the contents of the ring list,
starting with the first item added.
*/
intNode *bookmark = start;
while (start != NULL)
{
printf("%d ", start->number);
start = start->next;
if (start == bookmark) break;
}
printf("\n");
}
void freeList(intNode **start)
{
/* Free up memory allocated to linked ring list */
intNode *temp;
/* check that ring list is not empty */
if (*start == NULL) return;
/* remove all items, until one remaining in ring list */
while (*start != (*start)->next)
{
temp = (*start)->next;
(*start) = temp->next;
free(temp);
}
/* free up last remaining item in ring list */
free(*start);
*start = NULL;
}
intNode* newNode(int number)
{
/* dynamicaly allocate memory for an intNode
make sure it is initialised correctly
*/
intNode *temp;
temp = (intNode *) malloc(sizeof(intNode));
if (temp == NULL)
{
printf("WARNING - Memory allocation error\n");
exit(EXIT_FAILURE);
}
temp->number = number;
temp->next = NULL;
return temp;
}