I have a problem. I have an array of struct. In my program, I have two options or menu, which are add and delete. But, when I delete one element from the array, it will affect the other element's index. So, when I delete an element and do some addition, it will causes an error. How can I solve it?
Here is my code :
#include "stdio.h"
#include "string.h"
struct itemlist
{
char name[25];
int quantity;
};
int main()
{
int progress,processNum,i,sizeStruct = 0;
struct itemlist items[105];
printf("How many progress you want to do?\n");
scanf("%d",&progress); getchar();
for(i = 0; i < progress ; i++){
scanf("%d",&processNum); getchar();
switch (processNum){
case 1: // Add
printf("Name of item :\n");
scanf("%[^\n]",items[i].name); getchar();
printf("How many items?:\n");
scanf("%d",&items[i].quantity); getchar();
sizeStruct++;
printf("Success to add!!\n");
break;
case 2: // Delete from database, and its last index can be replaced.
int index3;
printf("Which index do you wanna delete?\n");
scanf("%d",&index3); getchar();
for(int k = index3-1; k < sizeStruct - 1; k++){
items[k] = items[k + 1];
}
sizeStruct--;
printf("Your item has been deleted.\n");
break;
}
}
// Scan All last Items
for(int j = 0; j < sizeStruct; j++){
printf("%s\n",items[j].name);
}
return 0;
}
This is the example of deleting the last index without addition, which is works :
How many progress you want to do?
3
1
Name of item :
Cola-Cola
How many items?:
3
Success to add!!
1
Name of item :
Sprite
How many items?:
1
Success to add!!
2
Which index do you wanna delete?
1
Your item has been deleted.
Sprite // List of items
Here is my code when i'm trying to add some element after I did some deletion.
How many progress you want to do?
4
1
Name of item :
Cola-Cola
How many items?:
3
Success to add!!
1
Name of item :
Sprite
How many items?:
4
Success to add!!
2
Which index do you wanna delete?
2
Your item has been deleted.
1
Name of item :
Beer
How many items?:
8
Success to add!!
Cola-Cola
Sprite // Supposed to be Beer, because Sprited already deleted.