c++ segmentation fault for dynamic arrays -
i want add theater object boxoffice object in c++ code. when try add in main code, first 1 added successfully. segmentation fault occurs second , obvioulsy other theater objects. here add function;
#include <iostream> #include <string> #include "boxoffice.h" using namespace std; boxoffice::boxoffice() { sizereserv = 0; sizetheater = 0; theaters = new theater[sizetheater]; reserv = new reservation[sizereserv]; } boxoffice::~boxoffice(){} void boxoffice::addtheater(int theaterid, string moviename, int numrows, int numseatsperrow){ bool theaterexist = false; for(int i=0; i<sizetheater; i++) { if(theaters[i].id == theaterid) { theaterexist=true; } } if(theaterexist) cout<<"theater "<<theaterid<<"("<<moviename<<") exists"<< endl; else { ++sizetheater; theater *temptheater = new theater[sizetheater]; if((sizetheater > 1)){ temptheater = theaters; } temptheater[sizetheater-1] = theater(theaterid,moviename,numrows,numseatsperrow); delete[] theaters; theaters = temptheater; cout<<"theater "<<theaterid<<"("<<moviename<<") has been added"<< endl; cout<<endl; delete[] temptheater; } }
and segmentation fault on line;
temptheater[sizetheater-1] = theater(theaterid,moviename,numrows,numseatsperrow);
this theater cpp;
#include "theater.h" using namespace std; theater::theater(){ id=0; moviename=""; numrows=0; numseatsperrow=0; } theater::theater(int theaterid, string theatermoviename, int theaternumofrows, int theaternumseatsperrow) { id = theaterid; moviename = theatermoviename; numrows = theaternumofrows; numseatsperrow = theaternumseatsperrow; theaterarray = new int*[theaternumofrows]; for(int i=0;i<theaternumofrows;i++) theaterarray[i]= new int[theaternumseatsperrow]; for(int i=0; i<theaternumofrows;i++){ for(int j=0;j<theaternumseatsperrow;j++){ theaterarray[i][j]=0; } } } header file of theater; #include <iostream> #include <string> using namespace std; class theater{ public: int id; string moviename; int numrows; int numseatsperrow; int **theaterarray; theater(); theater(int theaterid, string theatermoviename, int theaternumofrows, int theaternumseatsperrow); };
and how call add functions;
boxoffice r; r.addtheater(10425, "ted", 4, 3); r.addtheater(8234, "cloud atlas", 8, 3); r.addtheater(9176, "hope springs",6,2);
the problematic lines these:
if((sizetheater > 1)){ temptheater = theaters; }
first allocate memory , assign temptheater
, here overwrite pointer point old memory. not copy memory. since code homework assignment, i'll leave how copy data, hope follow the rule of three theater
class (as boxoffice
class) make simple.
also, there's no need allocate zero-size "array", make pointers nullptr
(or 0
).
Comments
Post a Comment