How to increment the index of an unlimited array?

0

How can I increment an array within a structure?

My structure is this:

struct list {
char name[50];
int products_list[]; } LIST[10];

I wanted to know the current number of elements in the array (list_products) to add more products with the right index.

My problem is: I use scanf to get user products so they can be unlimited. I tried to use the sizeof function but it did not work because it did not add the right indexes of the products.

posicao_atual = (sizeof(LISTA[opcao_lista].produtos_listas) / sizeof(int) + 1);

Thank you.

    
asked by anonymous 01.01.2017 / 23:03

1 answer

0

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 adding a new product, increment the counter. list_number is the number in the list.

list [list_number].product_list_size++;

Count Option 1

Use this counter for memory allocation. If a product is to be removed from the list, it is only necessary to decrease and allocate the products in the new positions.

Count Option 2

When deleting an item from the list, set it to -1 ( position is the position of the product in the list), without decreasing the product_list_size . You do not need to relocate the 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 integer size, according to the platform.

    
04.02.2017 / 06:50