The program i am working on i am trying to get it to display how many items are in a list. but i am trying to do it with a function. The program compiles correct and gives no errors but when i run the program and input some things when it displays the number of items in the list it only displays 1 and will not increment when new items are added. Can any one see what i am doing wrong. Thanks.
Code:
#include <stdio.h>
#include <conio.h>
#include <malloc.h>
struct item {char name[10];
int dollars, cents;
struct item *next_item;};
struct item * Get_item (void);
void Display_List (struct item * ptr);
int count_List (struct item * ptr);
int count = 0;
int ptr_total;
void main()
{ struct item *ptr2start_of_list = NULL;
struct item *ptr_temp = NULL;
struct item *ptr_total = NULL;
char response;
ptr2start_of_list = Get_item();
while (1)
{
//This displays the number of items in the List
printf("\nThere are %i in the list", count_List(ptr_total));
//count_List(ptr_total);
printf ("\nWould you like to add another item? (Y or N)\n");
fflush(stdin);
response = getch();
if (response == 'y')
{ ptr_temp = Get_item(); //creates and fills new item
ptr_temp->next_item = ptr2start_of_list; //move the pointers to insert into list
ptr2start_of_list = ptr_temp;
}
else break;
}
//this would be a good spot to display the list!!!
printf ("\nThe list contains: \n");
Display_List(ptr2start_of_list);
//This displays the number of items in the List
printf("\nThere are %i in the list", count_List);
//count_List(ptr_total);
fflush(stdin);
getch();
return;
}
struct item * Get_item (void)
{ struct item *ptr;
//create a space to store the info, then fill the space
ptr = (struct item *) malloc (sizeof (struct item));
printf("\nType an item name: ");
gets(ptr->name);
printf("\nType in a price, dollars first:");
scanf ("%i", &ptr->dollars);
fflush(stdin);
printf("\nNow cents: ");
scanf ("%i", &ptr->cents);
fflush(stdin);
ptr->next_item = NULL;
return (ptr);
}
void Display_List (struct item * ptr)
{
//traverse the list, displaying each member
while (ptr != NULL)
{
printf("\n.... %s, $%d.%.2d", ptr->name, ptr->dollars, ptr->cents);
ptr = ptr->next_item; //advance to next item in list
}
fflush(stdout);
return;
}
count_List (struct item * ptr)
{int counter = 1;
//Tracers the list. counting each member
while (ptr != NULL)
{
counter++;
ptr = ptr->next_item; //advance to next item in list
counter = ptr_total;
}
return (counter);
}