I have created a program to add 2 types of items in to a system. I have created 2 structures for the 2 different items. Currently i have created a method to add items to the system and i store each item in an array. However i encountered a problem when i was gonna implement the delete feature, the problem is if i have a record at array memory index 2, if i delete it there will be an unused space, between memory index 1 and 3. How can i overcome this ? In java , there is arraylist which dynamically allocates space. In C i know that there is dynamic memory allocation , but how can i implement it work with the delete feature ?
Here is what i have done so far :-
#include <stdio.h>
#include <string.h>
struct routers
{
int Device_No;
char Device_Name[30];
int No_of_items;
int Price;
char Description[30];
};
/**declared an of struct routers to store the structure objects
**/
struct routers routerlist[5];
struct controllers
{
int Device_No;
char Device_Name;
int No_of_items;
int Price;
char Description[30];
};
void AddNewItem();
int main()
{
AddNewItem();
return 0;
}
void AddNewItem(){
int item;
int choice=0;
int arraysize=0;
do{
printf("Press 1 to add a Router \nPress 2 to add a controller \n");
scanf("%d",&item);
printf("%d",item);
if(item==1){
printf("\nEnter Device No:\n");
scanf("%d",&routerlist[arraysize].Device_No);
printf("Enter Device Name\n");
fflush(stdin); //flush the buffer
gets(routerlist[arraysize].Device_Name);
printf("Enter Number of Items\n");
scanf("%d",&routerlist[arraysize].No_of_items);
printf("Enter price\n");
scanf("%d",&routerlist[arraysize].Price);
printf("Enter description\n");
fflush(stdin);
gets(routerlist[arraysize].Description);
}
arraysize++;
printf("Do you want to add another item? \nPress 1 to add \nPress 2 to Cancel\n");
scanf("%d",&choice);
}while(choice==1);
}
Thank you for your time.
fflush(stdin)is undefined behavior !! Also don't use gets its a kingkong of problems.fflush(stdin)might work for some systems but its undefined ...... usegetchar();instead after the input it will eatup the newline which remains in your buffer.