C++ program runs in linux but not windows - c++

I am writing this program for college and keep having problems with it. I wrote in using codeblocks in ubuntu and it runs fine no errors or anything. But when I run it in windows on codeblocks it crashes and I keep getting the same error "terminate called after throwing an instance of 'std::bad_alloc' what<>: std::badalloc' then it stops working.
Any help would be appreciated!
Thankyou
Ron
main.cpp
#include <iostream>
#include "set.h"
using namespace std;
int main()
{
Set Set1;
List List1;
List1.header();
int choice = 0;
int value = 0;
cout<<"Press 1 to use a list or press 2 for a set"<<endl;
cin>>choice;
if(choice == 1) //List
{
while(choice != 4)
{
value = 0;
List1.menu();
cin>>choice;
switch(choice)
{
case 1:cout<<"Please enter value"<<endl;
cin>>value;
List1.set_value(value);
break;
case 2:List1.print_list();
break;
case 3:List1.test_copy_constructor();
break;
}
}
}
else if(choice == 2) //Set
{
while(choice != 4)
{
value = 0;
List1.menu();
cin>>choice;
switch(choice)
{
case 1:cout<<"Please enter value"<<endl;
cin>>value;
Set1.set_value(value);
break;
case 2:Set1.print_list();
break;
case 3:Set1.test_copy_constructor();
break;
}
}
}
else
{
cout<<"Please Enter a valid option"<<endl;
}
return 0;
}
set.cpp
#include "set.h"
#include <iostream>
#include <string>
using namespace std;
//Constructor
List::List()
{
int array_size;
int *array = new int[array_size];
// delete [] array;
}
List List1;
//Print functions
void List::header(void) const
{
cout<<"Program Name: Program 2"<<endl;
cout<<"Program Created: March 20,2014"<<endl;
cout<<"Created by: Ron Miller"<<endl;
cout<<"--------------------------------"<<endl;
cout<<" "<<endl;
}
void List::menu(void) const
{
cout<<" Menu"<<endl;
cout<<"---------------------------------------------------------"<<endl;
cout<<"1. Insert (value to be inserted is entered from keyboard)"<<endl;
cout<<"2. Print List (all values, one per line)"<<endl;
cout<<"3. Test Copy Constructor (pass list by value to a function"<<endl;
cout<<" and from within the function change all values in list"<<endl;
cout<<" to 0, then call Print List before function ends)"<<endl;
cout<<"4. Quit"<<endl;
cout<<"---------------------------------------------------------"<<endl;
}
//Modification Functions
void List::set_value(const int value)
{
if (slot == 0) //If first run set array size
{
array = new int[array_size];
}
if (slot == array_size) //If array needs extended save data in temp array expand original array then copy back to original
{
cout<<"EXPAND ARRAY"<<endl;
temp_array = array;
array_size = array_size + 2;
array = new int[array_size];
array = temp_array;
}
array[slot] = value; //Set current array slot to value
slot = slot+1;
}
void List::print_list(void) const
{
int i = 0;
cout<<"---------------"<<endl;
while(i < slot)
{
cout<<array[i]<<endl;
i = i+1;
}
cout<<"---------------"<<endl;
}
void List::test_copy_constructor(void) const
{
int* test_array;
test_array = array;
int i = 0;
test_array = new int[array_size]; //Copy original array to test_Array
while(i < slot) //Set array to 0
{
test_array[i] = 0;
i = i+1;
}
i = 0;
cout<<"---------------"<<endl;
while(i < slot) //REMOVE THIS ONLY FOR TESTING PURPOSES
{
cout<<test_array[i]<<endl;
i = i+1;
}
i = 0;
cout<<"---------------"<<endl;
List::print_list(); //Print original array
}
void Set::set_value(const int value)
{
array = get_array(); //Use get functions to obtain copies of private data
temp_array = get_temp_array();
array_size = get_array_size();
temp_array_size = get_temp_array_size();
slot = get_slot();
char match;
match = Set::search_array(value);
if(match == 'y')
{
cout<<"Match"<<endl;
}
if(match == 'n')
{
if (slot == 0) //If first run set array size
{
array = new int[array_size];
}
if (slot == array_size) //If array needs extended save data in temp array expand original array then copy back to original
{
cout<<"EXPAND ARRAY"<<endl;
temp_array = array;
array_size = array_size + 2;
array = new int[array_size];
array = temp_array;
}
array[slot] = value; //Set current array slot to value
slot = slot+1;
set_array(array); //Use set values to update private data
set_temp_array(temp_array);
set_array_size(array_size);
set_temp_array_size(temp_array_size);
set_slot(slot);
}
}
char Set::search_array(int value)
{
array = get_array();
array_size = get_array_size();
slot = get_slot();
int array_value;
char match = 'n';
int i =0;
while(i < slot) //Searches array for a match if there is return y otherwise return n
{
if( array[i] == value)
{
match = 'y';
}
else
{
match = 'n';
}
i = i+1;
}
return match;
}
//Set Functions
void List::set_array(int* value)
{
array = value;
}
void List::set_array_size(int value)
{
array_size = value;
}
void List::set_temp_array(int* value)
{
temp_array = value;
}
void List::set_temp_array_size(int value)
{
temp_array_size = value;
}
void List::set_slot(int value)
{
slot = value;
}
//Get Functions
int* List::get_array(void) const
{
return array;
}
int* List::get_temp_array(void) const
{
return temp_array;
}
int List::get_array_size(void) const
{
return array_size;
}
int List::get_temp_array_size(void) const
{
return temp_array_size;
}
int List::get_slot(void) const
{
return slot;
}
set.h
#ifndef set_H_INCLUDED
#define set_H_INCLUDED
class List
{
public:
//Constructor
List();
//Print Functions
void header (void) const;
void menu (void) const;
//Modification Functions
void set_value (const int);
void print_list(void) const;
void test_copy_constructor(void) const;
//Set functions
void set_array( int*);
void set_temp_array(int*);
void set_array_size( int);
void set_temp_array_size(int);
void set_slot(const int);
//Get functions
int* get_array (void) const;
int* get_temp_array (void) const;
int get_array_size (void) const;
int get_temp_array_size (void) const;
int get_slot(void) const;
private:
int array_size;
int *array;
int *temp_array;
int temp_array_size;
int slot = 0;
};
class Set : public List
{
public:
//Modification Functions
void set_value (const int);
char search_array(const int);
private:
int array_size = 2;
int *array;
int *temp_array;
int temp_array_size = 2;
int slot = 0;
};
#endif

List::List()
{
int array_size;
int *array = new int[array_size];
// ...
}
What value is array_size supposed to have? How large an int array is supposed to be allocated?
It seems to me that this local variable declaration is superfluous; remove it, and use the member variable, instead. (You've initialised the member variable to 2 at its point of declaration, using a new C++11 feature which allows you to do so with a variable that is not static const.)
Don't forget to hand back that allocated memory when you're done with it. In general I would propose that you use std::vector for this.

Related

"No instance of constructor "PlayerData::PlayerData" matches the argument list." error Visual Studio is giving me when I try to run the program

Header File
#pragma once
#ifndef PLAYERDATA_H
#define PLAYERDATA_H
#include <string>
using namespace std;
class PlayerData
{
private:
Private member variables
static const int SIZE = 10;
string name; //Player Name
int jnum; //Jersey Number
string team; //Player Team
string position; //Player position
int points[SIZE]; // Array of points for last 10 games
int rebounds[SIZE]; // Array of rebounds for last 10 games
int assist[SIZE]; // Array of assist for last 10 games
double ap = 0.0; // Average number of points
double ar = 0.0; // Average number of rebounds
double aa = 0.0; // Average number of assits
public:
Constructor to initialize data if no data is passed
// Constructor #1
PlayerData()
{
jnum = 0;
name = "";
team = "";
position = "";
for (int i = 0; i < SIZE; i++)
{
points[SIZE] = 0;
rebounds[SIZE] = 0;
assist[SIZE] = 0;
}
}
// Constructor #2
Constructor to accept parameter. Collects jersey number, name, team name, position, array of points for last 10 games, array of rebounds for last 10 games, array of assist for last 10 games.
PlayerData( int jn, string n, string t, string pos, int p[SIZE], int r[SIZE], int a[SIZE])
{
jnum = jn;
name = n;
team = t;
position = pos;
for (int i = 0; i < SIZE; i++)
{
points[SIZE] = p[SIZE];
rebounds[SIZE] = r[SIZE];
assist[SIZE] = a[SIZE];
}
}
// Mutator Function
void setJersery(int jn)
{
jnum = jn;
}
void setName(string n)
{
name = n;
}
void setTeam(string t)
{
team = t;
}
void setPosition(string pos)
{
position = pos;
}
void setPoints(int p[SIZE])
{
for (int z = 0; z < SIZE; z++)
{
points[SIZE] = p[SIZE];
}
}
void setRebounds(int r[SIZE])
{
for (int z = 0; z < SIZE; z++)
{
rebounds[SIZE] = r[SIZE];
}
}
void setAssist(int a[SIZE])
{
for (int z = 0; z < SIZE; z++)
{
assist[SIZE] = a[SIZE];
}
}
// Acessor methods
string getName()
{
return name;
}
int getJersey()
{
return jnum;
}
string getTeam()
{
return team;
}
string getPosition()
{
return position;
}
int getPoints()
{
return points[SIZE];
}
int getRebounds()
{
return rebounds[SIZE];
}
int getAssist()
{
return assist[SIZE];
}
/*
double averageP(int p[], const int SIZE);
double averageR(int r[], const int SIZE);
double averageA(int a[], const int SIZE);
*/
void averageP(int p[], const int SIZE);
void averageR(int r[], const int SIZE);
void averageA(int a[], const int SIZE);
double getAP()
{
return ap;
}
double getAR()
{
return ar;
}
double getAA()
{
return aa;
}
};
#endif // !PLAYERDATA_H
Calculates average points,rebounds, assist from the arrays that were passed.
PlayerData.cpp
#include "PlayerData.h"
using namespace std;
// Calculate average points
void PlayerData::averageP(int p[], const int s)
{
for (int c = 0; c < s; c++)
{
ap += p[c];
}
ap /= s;
//return ap;
}
// Calculate average rebounds
void PlayerData::averageR(int r[], const int s)
{
for (int c = 0; c < s; c++)
{
ar += r[c];
}
ar /= s;
//return ar;
}
// Calculate average assist
void PlayerData::averageA(int a[], const int s)
{
for (int c = 0; c < s; c++)
{
aa += a[c];
}
aa /= s;
//return aa;
}
Main
#include <iostream>
#include <iomanip>
#include "PlayerData.h"
using namespace std;
int main()
{
const int SIZE = 10;
int points[SIZE] = { 10,10,10,10,10,10,10,10,10,10 };
int assist[SIZE] = { 2,2,2,2,2,2,2,2,2,2, };
int rebounds[SIZE] = { 3,3,3,3,3,3,3,3,3,3 };
Here is where the problem occurs. The compiler marks under the 6 as if the int is not part of the arguments for the constructor. I'm not sure why it is doing this. I receive this message "No instance of constructor "PlayerData::PlayerData" matches the argument list."
PlayerData player1(6, "Jimmy Butler", "Chicago Bulls", "Forward", points[SIZE], rebounds[SIZE], assist[SIZE]);
getchar();
return 0;
}
Constructor requires an array of integers and in main you are passing a pointer to int. If you want to pass the whole array you should delete the [SIZE] because that is translated as (if SIZE is 5 for example) "give me the 6th element of 5 element array".
Try calling it like this.
PlayerData player1(6, "Jimmy Butler", "Chicago Bulls", "Forward", points, rebounds, assist);

Create a randomly connected set of nodes?

I'm trying to write a function, generate_labyrinth(), that creates a fixed number of randomly connected nodes. Each node is connected with three other nodes.
Here is what I have now:
labyrinth.h:
#ifndef LABYRINTH_H
#define LABYRINTH_H
// node
class Room {
public:
Room ()
: room_number(0), left_door(nullptr),
center_door(nullptr), right_door(nullptr) { }
// data member
int room_number;
// pointers to other nodes
Room* left_door;
Room* center_door;
Room* right_door;
};
//=================================================
class Labyrinth {
public:
Labyrinth (int s) : size(s) { generate_labyrinth (); }
private:
// number of nodes
int size;
// root node
Room* entrance;
// Helper functions
int random_number (int from, int to);
int random_number_without_i (int min, int max, int i);
// Initialiazation function
void generate_labyrinth ();
};
#include "labyrinth.cpp"
#endif
labyrinth.cpp:
// Class Labyrinth member implementations
int Labyrinth::random_number (int min, int max) {
static bool seed_initialized = false;
if (!seed_initialized) {
seed_initialized = true;
srand((unsigned int) time(NULL));
}
return rand() % (max - min + 1) + min;
}
int Labyrinth::random_number_without_i (int min, int max, int i) {
int res = random_number(min, max);
while (res == i){
res = random_number(min, max);
}
return res;
}
void Labyrinth::generate_labyrinth () {
// create "size" number of nodes
entrance = new Room[size];
// initialize Room (node) data members
for (auto i = 0; i < size; ++i) {
entrance[i].room_number = i;
}
// connect each room with three others
int first_room = 1;
int last_room = size - 1;
for (int i = 1; i < size; ++i) {
// avoid connecting a room with itself
int left_goes_to = random_number_without_i (first_room, last_room, i);
int center_goes_to = random_number_without_i (first_room, last_room, i);
int right_goes_to = random_number_without_i (first_room, last_room, i);
entrance[i].left_door = (&entrance[left_goes_to]);
entrance[i].center_door = (&entrance [center_goes_to]);
entrance[i].right_door = (&entrance [right_goes_to]);;
}
// TEST IF NODES POINT TO EACH OTHER
for (auto i = 0; i < size; ++i) {
if (entrance[i].left_door == nullptr || entrance[i].center_door == nullptr ||
entrance[i].right_door == nullptr) {
std::cout <<"Uninitialized pointer value\n";
}
}
getchar();
}
main:
#include <iostream>
#include <time.h>
#include "labyrinth.h"
//=================================================
int main()
{
int cave_size = 20;
Labyrinth cave(cave_size);
}
It appears that after the node initialization in generate_labyrinth () the three pointers, left_room, center_room, right_room remain uninitialized, i.e. the output I get is :
Uninitialized pointer value
Questions:
Why aren't the pointers in the nodes initialized?
Is there another way to generate a randomly connected set of nodes?
Note: I'm not using an insert() function as the number of nodes is fixed and determined during the construction of the data structure.
You generate connections for first_room to last_room, which are rooms 1 to size-1.
// connect each room with three others
int first_room = 1;
int last_room = size - 1;
for (int i = 1; i < size; ++i) {
But when you check the connections you start with room 0 (probably supposed to be the entrance itself).
// TEST IF NODES POINT TO EACH OTHER
for (auto i = 0; i < size; ++i) {

Building a 2D array class from a 1D array class in C++

in my C++ class we are finally getting conceptually fairly deep (well, relatively!) and I'm struggling with building a class from a previous class.
Here is my first class header, which builds partially filled array objects. To my knowledge, it is fully functional:
#ifndef PARTIALARRAY_H
#define PARTIALARRAY_H
#include <iostream>
#include <string.h>
using namespace std;
typedef int ITEM_TYPE;
ITEM_TYPE const MAX = 50;
class PartialArray
{
public:
//-----------------------------------------ctors:-----------------------------------------
PartialArray();
PartialArray(const int init[], int used);
//-----------------------------------------member functions:-----------------------------------------
void PrintArray();
int Search(ITEM_TYPE key);
int Append(ITEM_TYPE appendMe);
int ShiftRight(int shiftHere);
int ShiftLeft(int shiftHere);
int InsertBefore(ITEM_TYPE insertThis, int insertHere);
int InsertAfter(ITEM_TYPE insertThis, int insertHere);
int Delete(int deleteHere);
void DeleteRepeats();
int NumUsed();
void Sort();
void Reverse();
string ErrorDescr(int failCode);
//-----------------------------------------operators:-----------------------------------------
ITEM_TYPE& operator [] (ITEM_TYPE x);
private:
//-----------------------------------------member vars:-----------------------------------------
ITEM_TYPE a[MAX];
int numUsed;
};
#endif // PARTIALARRAY_H
And here are the class functions:
#include "partialarray.h"
#include <iostream>
#include <string.h>
using namespace std;
//-----------------------------------------ctors:-----------------------------------------
PartialArray::PartialArray()
{
numUsed=0;
}
PartialArray::PartialArray(const int init[], int used)
{
numUsed = used;
for(int i=0; i<numUsed; i++)
{
a[i]=init[i];
}
}
//-----------------------------------------member functions:-----------------------------------------
//Prints the array up to its last used element
void PartialArray::PrintArray()
{
for(int i=0; i<numUsed; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
//Searches the array for a particular value and returns the index at which the value first appears
int PartialArray::Search(ITEM_TYPE key)
{
for(int i=0; i<numUsed; i++)
{
if(a[i]==key)
return i;
}
return -1;
}
//Takes a number and appends it to the end of the array after the last interesting element
int PartialArray::Append(ITEM_TYPE appendMe)
{
if(numUsed<MAX)
a[numUsed++] = appendMe;
else
return 1;
return 0;
}
//Shifts all elements of the array to the right starting at a particular index
int PartialArray::ShiftRight(int shiftHere)
{
if(shiftHere<numUsed)
{
ITEM_TYPE save = a[numUsed-1];
for(int i=numUsed; i>=shiftHere; i--)
{
a[i] = a[i-1];
}
a[shiftHere] = save;
return 0;
}
else
return 2;
}
//Shifts all elements of the array to the left starting at a particular index
int PartialArray::ShiftLeft(int shiftHere)
{
if(shiftHere<numUsed)
{
ITEM_TYPE save = a[shiftHere];
for(int i=shiftHere; i<numUsed; i++)
{
a[i] = a[i+1];
}
a[numUsed-1] = save;
return 0;
}
else
return 2;
}
//Takes a number and a position and inserts the number before that position in the array shifting the elements to the right
int PartialArray::InsertBefore(ITEM_TYPE insertThis, int insertHere)
{
if(insertHere>numUsed)
return 2;
else
{
numUsed++;
ShiftRight(insertHere);
a[insertHere] = insertThis;
}
return 0;
}
//Takes a number and a position and inserts the number after that position in the array shifting the elements to the right
int PartialArray::InsertAfter(ITEM_TYPE insertThis, int insertHere)
{
if(insertHere>numUsed)
return 2;
else if(numUsed>=MAX)
return 1;
else
{
numUsed++;
ShiftRight(insertHere+1);
a[insertHere+1] = insertThis;
}
return 0;
}
//Takes a position and removes that item from the array, shifting all the elements to the left
int PartialArray::Delete(int deleteHere)
{
if(deleteHere <= numUsed)
{
ShiftLeft(deleteHere);
numUsed--;
return 0;
}
else
return 2;
}
//Deletes repeated elements in the array and replaces the with 0
void PartialArray::DeleteRepeats()
{
for(int i=0;i<numUsed;i++)
{
ITEM_TYPE n=a[i];
for(int j=i+1; j<numUsed;j++)
{
if(n == a[j])
{
Delete(j);
j--;
}
}
}
}
//Returns number of interesting elements in the array
int PartialArray::NumUsed()
{
return numUsed;
}
//Utilizes a bubble sort algorithm
void PartialArray::Sort()
{
bool swap = true;
int j = 0;
int save;
while (swap==true)
{
swap = false;
j++;
for (int i = 0; i < numUsed - j; i++)
{
if (a[i] > a[i + 1])
{
save = a[i];
a[i] = a[i + 1];
a[i + 1] = save;
swap = true;
}
}
}
}
void PartialArray::Reverse()
{
for(int i=0;i<numUsed-1;i++)
{
ITEM_TYPE save = a[numUsed-1];
ShiftRight(i);
a[i] = save;
}
}
//Returns the appropriate error description for a particular fail code
string PartialArray::ErrorDescr(int failCode)
{
switch(failCode)
{
case -1:
return "ERROR: item not found";
break;
case 1:
return "ERROR: array is full";
break;
case 2:
return "ERROR: unused index";
break;
default:
return "UNKNOWN ERROR";
break;
}
}
//-----------------------------------------operators:-----------------------------------------
ITEM_TYPE& PartialArray::operator [](ITEM_TYPE x)
{
return a[x];
}
Now, here is where things have gotten tricky. To build the two dimensional array class, I'm supposed to create an array of arrays. I'm at a loss as to how I should go about this, and after tinkering and googling for a few hours I've only become more confused. Specifically, the <<, [], and [](constant version) operators and the TwoDArray constructor have thrown me for a loop, and I'm stuck without much sense of what to do next. Here is the TwoD header file:
#ifndef TWODARRAY_H
#define TWODARRAY_H
#include "partialarray.h"
#include <iostream>
#include <string.h>
typedef int ITEM_TYPE;
class TwoDArray
{
friend ostream& operator << (ostream &outs, const TwoDArray& printMe);
public:
//ctors:
TwoDArray();
//member functions:
//PartialArray& operator [](int index); //[ ] operator for the TwoDArray object
//PartialArray operator [](int index) const; //[ ] operator for the TwoDArray object (const version)
int Append(int appendMe, int row);
int InsertBefore(int insertMe, int row, int column);
int InsertAfter(int insertMe, int row, int column);
int Delete(int row, int column);
bool Search(ITEM_TYPE key, int &row, int &column);
private:
//member vars:
PartialArray a[MAX];
};
#endif // TWODARRAY_H
And this is what I've tried to define thus far:
TwoDArray::TwoDArray()
{
const int array0[]= {0};
PartialArray array(array0, MAX);
}
ostream& operator << (ostream &outs, const TwoDArray& printMe)
{
for(int i=0;i<MAX;i++)
{
outs << printMe.a[i];
}
return outs;
}
Ideally, the << operator will print an m by n array of items.

Hi, I very confused on why I am getting a compilation error mainly: "Library.cc:(.text+0x27): undefined reference to `PatronArray::PatronArray()'"

this my Library.h file, before the Library used to do All the dirty work: in term of manipulating the arrays and stuff, but now I am trying to make the Library the middle man that just invoke the call that has to do with any array manipulations. My problem is I am trying to have one instance of Patron array, that would hold all the patrons in the Library.
#ifndef LIBRARY_H
#define LIBRARY_H
#include <string>
#include "types.h"
#include "Book.h"
#include "Patron.h"
#include "PatronArray.h"
//class PatronArray
class Library
{
public:
Library();
~Library();
void init();
int addBook(Book*);
int addPatron(Patron*);
int remPatron(int);
int findBook(int, Book**, int*);
int findPatron(string, string, Patron**, int*);
int getMaxCollIndex();
int getMaxPatronsIndex();
Book* getBook(int);
Patron* getPatron(int);
private:
Book* collection[MAX_COLL_SIZE];
PatronArray* patrons;
int maxCollIndex;
int maxPatronsIndex;
};
#endif
This is my Library.cc file
#include "Library.h"
Library::Library()
: maxCollIndex(0)
{
patrons = new PatronArray;
for (int i=0; i<MAX_COLL_SIZE; ++i) {
collection[i] = 0;
}
}
Library::~Library()
{
delete patrons;
for (int i=0; i<maxCollIndex; ++i)
delete collection[i];
}
int Library::getMaxCollIndex() { return maxCollIndex; }
int Library::getMaxPatronsIndex()
{
return patrons->getMaxPatronsIndex();
}
Book* Library::getBook(int index)
{
if (index < 0 || index >= maxCollIndex)
return 0;
return collection[index];
}
Patron* Library::getPatron(int index)
{
return patrons->getPatron(index);
}
void Library::init()
{
Book* newBook;
Patron* newPatron;
newBook = new Book("Ender's Game", "Orson Scott Card", 1985);
addBook(newBook);
newBook = new Book("Dune", "Frank Herbert", 1965);
newBook->setStatus(LOST);
addBook(newBook);
newBook = new Book("Foundation", "Isaac Asimov", 1951);
addBook(newBook);
newBook = new Book("Hitch Hiker's Guide to the Galaxy", "Douglas Adams", 1979);
addBook(newBook);
newPatron = new Patron("Jack", "Shephard");
addPatron(newPatron);
}
int Library::addBook(Book* book)
{
if (maxCollIndex >= MAX_COLL_SIZE - 1) {
return C_NOK;
}
collection[maxCollIndex++] = book;
return C_OK;
}
int Library::addPatron(Patron* patron)
{
// the lbrary is the middle ma that invokesthe calls
//return patronArray->addPatron(patron);
return patrons->addPatron(patron);
}
int Library::remPatron(int index)
{
return patrons->remPatron(index);
}
int Library::findPatron(string fn, string ln, Patron** patron, int* index)
{
return patrons->findPatron(fn,ln,patron,index);
}
int Library::findBook(int id, Book** book, int* index)
{
for (int i=0; i<maxCollIndex; ++i) {
if (collection[i] == 0)
continue;
if (collection[i]->getId() == id) {
*book = collection[i];
*index = i;
return C_OK;
}
}
*book = 0;
*index = -1;
return C_NOK;
}
This is my PatronArray.h that holds all the Patrons registered within the Library.
#ifndef PATRONARRAY_H
#define PATRONARRAY_H
#include "Patron.h"
#include "Book.h"
#include "types.h"
//class Patron;
class PatronArray
{
public:
PatronArray();
~PatronArray();
int addPatron(Patron*);
int remPatron(int);
int findPatron(string, string, Patron**, int*);
int getMaxPatronsIndex();
Patron* getPatron(int);
private:
Patron* patrons[MAX_COLL_SIZE];
int maxPatronsIndex;
};
#endif
and this is the PatronArray.cc file and please, I know there is better way of doing this by doing templating which I currently dont understand yet plus this way helps me understand the whole object oriented style.
#include<iostream>
#include<string>
#include "PatronArray.h"
/*
* Default constructor: recheck this later
*/
PatronArray::PatronArray()
:maxPatronsIndex(0)
{
for (int i = 0; i < MAX_COLL_SIZE; ++i) {
patrons[i] = 0;
}
}
/*
* Destructor: recheck this later
*/
PatronArray::~PatronArray()
{
for (int i = 0; i < maxPatronsIndex; ++i)
delete patrons[i];
}
//get the maxindex
int PatronArray::getMaxPatronsIndex() { return maxPatronsIndex; }
/*
* Adds the given Patron to the given patrons Array
*/
int PatronArray::addPatron(Patron* patron)
{
if (maxPatronsIndex >= MAX_COLL_SIZE - 1) {
return C_NOK;
}
patrons[maxPatronsIndex++] = patron;
return C_OK;
}
/*
* Used for removing a patron in the patrons array
*/
int PatronArray::remPatron(int index)
{
if (index < 0 || index >= maxPatronsIndex)
return C_NOK;
delete patrons[index];
patrons[index] = 0;
return C_OK;
}
/*
* Searches for the patron; if found, sets the contents of the second
* parameter to that patron pointer, sets the contents of the third parameter to
* its index in the collection, and returns C_OK; if not found, sets the
* contents of the second parameter to zero, the theird to -1, and returns C_NOK
*/
int PatronArray::findPatron( string fn, string ln, Patron** patron, int* index)
{
for (int i = 0; i < maxPatronsIndex; ++i) {
if (patrons[i] == 0)
continue;
if (patrons[i]->getFname() == fn && patrons[i]->getLname() == ln) {
*patron = patrons[i];
*index = i;
return C_OK;
}
}
*patron = 0;
*index = -1;
return C_NOK;
}
Patron* PatronArray::getPatron(int index)
{
if (index < 0 || index >= maxPatronsIndex)
return 0;
return patrons[index];
}
I forgot to link my PatronArray.cc to Library.cc in my makefile, thank you Jack!

Adding values to dynamic array

So I have this code, but it is not outputting, after adding 4th value, the right stuff, it's like it all gets deleted and it is not added until the next run
#include <iostream>
using namespace std;
const int DEFAULT_CAPACITY = 2;
void addValue(int data[], int& logSize, int& physSize, int newValue)
{
// DATA DICTIONARY
int *temp;
if (logSize == physSize)
{
physSize *= 2;
temp = new int[physSize];
for (int i = 0; i <= logSize; i++)
{
temp[i] = data[i];
cout<<temp[i]<<endl;
}
delete [] data;
data = temp;
}
data[logSize] = newValue;
for (int i = 0; i <= logSize; i++)
{
cout<<data[i]<<endl;
}
logSize++;
}
void printData(int data[], int logSize)
{
cout<<endl;
cout<<"ARRAY DATA:"<<endl;
for (int i = 0; i < logSize; i++)
{
cout<<data[i]<<endl;
}
}
void main()
{
//DATA DICTIONARY
int *data;
int logSize;
int physSize;
int newValue;
char choice;
physSize = DEFAULT_CAPACITY;
logSize = 0;
data = new int[physSize];
do
{
cout<<"What would you like to do?"<<endl;
cout<<"(A)dd value to array"<<endl;
cout<<"(D)isplay all values"<<endl;
cout<<"(Q)uit"<<endl;
cin>>choice;
if (choice == 'A' || choice == 'a')
{
cout<<"What integer do you want to add? ";
cin>>newValue;
addValue(data, logSize, physSize, newValue);
}
if (choice == 'D' || choice == 'd')
{
printData(data, logSize);
}
cout<<endl;
} while (choice != 'Q' && choice != 'q');
}
The fact that you could and should use an std::vector<int> aside, data is being passed as a pointer by value here:
void addValue(int data[], int& logSize, int& physSize, int newValue)
(for int data[], read int* data). So `addValue has its own copy of the pointer, and whatever it does with it has no effect on the caller side. You can fix this particular problem by passing the pointer by reference:
void addValue(int*& data, int& logSize, int& physSize, int newValue)
Pass the data by reference. You are passing it by value.