How to increment the index of an unlimited array?

Asked

Viewed 477 times

1

How can I increment an array within a structure?

This is my structure:

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

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

My problem is: I use the scanf to get the user products, so they can be unlimited. I tried using sizeof function but it didn’t work because it didn’t add right the products index’s.

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

Thank you.

  • 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?

  • 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.

  • Try to suffer more in the problem. What is your goal at the end of all this?

  • 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.

  • 1

    @Antoniofreitas the two accounts are yours, right? You want us to put them together? Which of the two must survive?

1 answer

1

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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.