user3348712
user3348712

Reputation: 161

function calling another functions gives wrong output c++?

The incrementStock function calls the "addProduct" function only if the sku string given in the argument matches with a member of the "inventory" array (the array is of type *Product and of size 50). I initialized the array to nullptr in the constructor. "num" is the increment number. When I test it and enter a valid sku to incrementStock, I get "no space" from the addproduct function.

void Supplier::addProduct(Product *p)
{
bool space = false;
int counter=0;
        while(!space && counter < inventory.size() )
        {
                if(inventory[counter] == nullptr )
                {
                        inventory[counter] = p;
                        space = true;
                }
        counter++;
        }

        if (!space)
        {
                cout << "no space" << endl;
        }

}


void Supplier::incrementStock(const string &sku, int num)
{
bool found = false;
        for( int i = 0; i < inventory.size(); i++ )
        {
                if( inventory[i] && sku == inventory[i]->getSKU())
                {
                        found=true;
                        addProduct(inventory[i]);
                        inventory[i]->setQuantity(inventory[i]->getQuantity() +num);
                }
        }

        if (found ==false)
        {
                cout << "not found" << endl;
        }
}

Upvotes: 0

Views: 80

Answers (1)

sj0h
sj0h

Reputation: 912

Consider this loop:

    for( int i = 0; i < inventory.size(); i++ )

If you get a match for sku within this loop, it will add an extra copy of that item into inventory. That's a bit odd, but fine if you want multiple copies of the same pointer in inventory.

The problem is that after that iteration of the loop, the loop will continue, and it will also find the copy we just made, and see that it matches, and then make another copy again. This repeats until the array is full.

Upvotes: 1

Related Questions