Hi to all, I have a homework about a banking system. I try to adding a branch in an array and the size of array dynamically increased. Here is my code but it gives run time error.

#include "BankingSystem.h"
#include "Branch.h"
#include <iostream>
using namespace std;
BankingSystem::BankingSystem(){
    size=0;
    branches=NULL;
}

void BankingSystem:: addBranch( const int branchId, const string branchName ){
    Branch b= Branch(branchId, branchName);
    if(size==0){
        size++;
        branches=new Branch[size];
        branches[0]=b;
        cout <<"Branch "<< b.getBranchId()<< " has been added."<<endl;
    }
    else{
        for(int i=0;i<size;i++)
            if(branches[i].getBranchId()==b.getBranchId()){
                cout<<"Branch "<<b.getBranchId()<<" already exists."<<endl;
                return;
            }
        int newsize= size++;
        Branch *temp=new Branch[newsize];
        for(int i=0;i<size;i++){
            temp[i]=branches[i];
        }
        temp[size]=b;
        
        cout <<"Branch "<< b.getBranchId()<< " has been added."<<endl;
        delete[] branches;
        branches=temp;

    }
}

Recommended Answers

All 2 Replies

int newsize= size++;
        Branch *temp=new Branch[newsize];
        for(int i=0;i<size;i++){
            temp[i]=branches[i];
        }
        temp[size]=b;

Let's say size is 10. So newsize is also 10. Then you increase size and now size=11. So your loop goes from 0 to 10. But temp[10] doesnt exist. Also temp (which is temp[11] in this example) doesnt exist.

int newsize= size++;
        Branch *temp=new Branch[newsize];
        for(int i=0;i<size;i++){
            temp[i]=branches[i];
        }
        temp[size]=b;

Let's say size is 10. So newsize is also 10. Then you increase size and now size=11. So your loop goes from 0 to 10. But temp[10] doesnt exist. Also temp (which is temp[11] in this example) doesnt exist.

thanks for your help, but my fault is not same as your saying.yes lets assume size is 10 and with loop I copied the elements from the branches array to temp array which size is 11.(newsize is eleven) .then I say temp (which is temp[10] so it exist) I solved this problem by saying

int newsize=size+1;

and I update size by saying

size=newsize;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.