Trying to delete product from my list using pointer and struct

42 Views Asked by At

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;

    }
}
2

There are 2 best solutions below

0
On

It seems that the data members productName and unit are character arrays and arrays do not have the assignment operator.

To copy strings stored in character arrays you should use the standard C function strcpy declared in the header <string.h> as for example

strcpy( list->itemList[i].productName, list->itemList[i + 1].productName );

But 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 memmove declared in the same header <string.h> as for example

memmove( list->itemList + itemToDelet - 1, 
         list->itemList + itemToDelet,
         ( list->length - itemToDelet ) * sizeof( *list->itemList ) );

--list->length;

Also before the call of memmove you need to check that the value of itemToDelet is greater than 0.

0
On

To copy the contents of a string (e.g. type char[10]), use strcpy. Arrays of characters cannot be assigned, just copied.

strcpy(list->itemList[i].productName,list->itemList[i + 1].productName);