In this function, I trying to delete a product from a list. Visual Studio shows me a red line under
list->itemList[i].productName = list->itemList[i + 1].productName;
and
list->itemList[i].unit = list->itemList[i + 1].unit;
but not under
list->itemList[i].amount = list->itemList[i + 1].amount;
The productName and unit is char, and the amount is float.
void removeItem(struct ShoppingList *list){
int itemToDelet;
while (1) {
for (int i = 0; i < list->length; i++) {
printf("%d. %s \t %.2f \t %s\n", i + 1, list->itemList[i].productName, list->itemList[i].amount, list->itemList[i].unit);
}
printf("\n\nWhich product do you want to remove? ");
scanf("%d", &itemToDelet);
if (itemToDelet <= list->length) {
for (int i = 0; i < list->length; i++) {
if (itemToDelet == i + 1) {
for (int i = 0; i < list->length; i++) {
list->itemList[i].productName = list->itemList[i + 1].productName;
list->itemList[i].amount = list->itemList[i + 1].amount;
list->itemList[i].unit = list->itemList[i + 1].unit;
list->length--;
}
break;
}
break;
}
}
else {
printf("\nThe list contains only %d items!", list->length);
}
break;
}
}
It seems that the data members
productNameandunitare character arrays and arrays do not have the assignment operator.To copy strings stored in character arrays you should use the standard C function
strcpydeclared in the header<string.h>as for exampleBut in any case your function is incorrect and invokes undefined behavior. The for loops within the function do not make a sense.
Instead of the for loops you could use another standard C function
memmovedeclared in the same header<string.h>as for exampleAlso before the call of
memmoveyou need to check that the value ofitemToDeletis greater than0.