include a variable with the size of the list: unsigned int product_list_size
.
typedef struct {
char name [50];
unsigned int product_list_size;
int products_list [];
} list_t;
// ...
list_t list [10];
list.product_list_size = 0;
// Inicialização da lista...
When including a new product, increment the counter. list_number
is the number on the list.
list [list_number].product_list_size++;
Option 1 of Count
Use this counter for memory allocation. If you are going to remove a product from the list, simply decrement and allocate the products in the new positions.
Option 2 of Count
When deleting an item from the list, set to how -1
(position
is the position of the product in the list), without decreasing the product_list_size
. No need to relocate memory.
list [list_number].products_list [position] = -1;
To count just go through the list and discard the negative values
unsigned int product_list_size = 0;
for (unsigned int _position; _position < list [list_number].product_list_size; _position++) {
if (list [list_number].products_list [_position] > 0)
product_list_size++;
Do not forget that the maximum size of the list will be the maximum size of the integer, according to the platform.
Ah, and by the way, what’s stopping you from putting a counter like
int
within the structure to tell how many items are filled?– Victor Stafusa
My problem is, I have several shopping lists. You can insert 3 products into one, exit the product insertion area and return at any time. That’s when I need to know, that exactly on that list there are 3 products. With the counter I would increment to any list.
– António Freitas
Try to suffer more in the problem. What is your goal at the end of all this?
– Not The Real Hemingway
Ué, just create a function to add items in the list, receiving it as parameter and the item to be added. Then, you increment the variable that indicates the quantity and enter. I remember making such lists in the discipline of Data Structure, and this problem was solved like this.
– mau humor
@Antoniofreitas the two accounts are yours, right? You want us to put them together? Which of the two must survive?
– Maniero