Home > database >  Trying to add an element to a dynamic array
Trying to add an element to a dynamic array

Time:05-27

i've tried to add an element from class type to an empty dynamic array, but nothing happens, nor it changes the counter after adding one element. This is the function

void Bank::addCustomer(const Customer& newCustomer) {

    Customer* temp = new Customer[getCustomerCount() 1]; 

    for (int i = 0; i < getCustomerCount()   1 ;   i) {
        if (getCustomerCount() != 0) {
            temp[i] = customers[i];
        }
    }

      customerCount;
    setCustomerCount(customerCount);
    delete[] customers; 
    customers = temp;

    customers[customerCount] = newCustomer; 
    //log
}

CodePudding user response:

Your loop is exceeding the bounds of the old array if it is not empty. And your assignment of the newCustomer is exceeding the bounds of the new array.

Try this instead:

void Bank::addCustomer(const Customer& newCustomer) {

    int count = getCustomerCount(); 
    Customer* temp = new Customer[count   1];

    for (int i = 0; i < count;   i) {
        temp[i] = customers[i];
    }
    temp[count] = newCustomer; 

    delete[] customers; 
    customers = temp;

      customerCount;

    //log
}

CodePudding user response:

I'm guessing this is what you mean:

void addCustomer(const Customer& newCustomer) {
    int old_customer_count = getCustomerCount();
    int new_customer_count = old_customer_count   1;

    Customer* temp = new Customer[new_customer_count];
    for (int i = 0; i < new_customer_count;   i) {
        temp[i] = customers[i];
    }

    setCustomerCount(new_customer_count);
    delete[] customers;
    customers = temp;
    customers[old_customer_count] = newCustomer;
}

but as someone said, in real code you should an std::vector for the customers collection.

  • Related