Adding values to dynamic array - c++

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.

Related

C++ implementation of stack using array

I have studied the algorithm from Introduction to Algorithm and then
I have written this code. But in my output another value is showing for index 0. and when I use pop function it display 1 instead of 3
#include <iostream>
int top;
void initialise_top(){
top = -1;
}
bool stack_empty(int a[]){
if(top == -1)
return true;
else
return false;
}
void push(int a[], int x, int s){
if(top < s - 1){
top = top + 1;
a[top] = x;
}
else
std::cout << "overflow" << "\n";
}
int pop(int a[]){
if (stack_empty(a) == true)
std::cout << "Underflow" << "\n";
else{
--top;
return a[top+1];
}
}
void display(int a[]){
for(int i = 0;i <= top; i++){
std::cout << a[i] << " ";
}
}
int main()
{
int arr[7];
push(arr,15,7);
push(arr,6,7);
push(arr,2,7);
push(arr,9,7);
push(arr,17,7);
push(arr,3,7);
display(arr);
std::cout << "\n";
int out = pop(arr);
std::cout << pop << "\n";
return 0;
}
Here is the snapshot of the output
enter image description here
In your implementatiton you have "initialise_top()" function.
void initialise_top(){
top=-1;
}
But you don't call it in main function. If you don't call it you can't initialize "top" variable and "top" variable will hold garbage value.
You can read details in here :
Default variable value
And also in theese lines you have some mistakes:
int out=pop(arr);
std::cout<<pop<<"\n";
you must print "out" variable :
std::cout << out << "\n";
You can look to corrected code for your implementation in here :
https://repl.it/JaOd/0
I have this stack array code in C. You can use it as your guide in implementing it to C++.
#include <stdio.h>
#include <stdlib.h>
void push(void);
void pop(void);
int a[5];
int top = -1;
int counter = 0;
int choice;
main() {
do{
printf("*********************************************\nSTACK\nPress the
corresponding button you desire.\n\nPress 1 to push a number to
stack.\nPress 2 to display the current stack.\nPress 3 to pop the current
stack.\nPress 0 to exit.\n\n");
scanf("%d", &choice);
if(choice == 0){
choice = 0;
}
else if(choice == 1){
push();
}
else if(choice == 2){
int i;
printf("Current Stack:\n");
for(i = 0;i <= 4;i++){
printf("%d", a[i]);
}
printf("\n\n");
}
else if(choice == 3){
pop();
}
}while(choice != 0);
}
void push(){
if(top <= 3){
int input;
printf("Enter number to push: ");
scanf("%d", &input);
top = top + 1;
a[top] = input;
int i;
printf("Current Stack:\n");
for(i = 0;i <= 4;i++){
printf("%d", a[i]);
}
printf("\n\n");
}else{
printf("Out of Bounds\n\n");
exit(0);
}
}
void pop(){
if(top >= 0){
printf("You just popped: ");
printf("%d \n\n", a[top]);
a[top] = 0;
printf("Current Stack:\n");
int i;
for(i = 0;i <= 4;i++){
printf("%d", a[i]);
}
printf("\n\n");
top = top - 1;
}else{
printf("Out of Bounds\n\n");
exit(0);
}
}
#include <iostream>
int top;
void initialise_top(){
top=-1;}
bool stack_empty(int a[]){
if(top==-1)
return true;
else
return false;
}
void push(int a[],int x,int s){
if(top<s-1){
top=top+1;
a[top]=x;
}
else
std::cout<<"overflow"<<"\n";
}
int pop(int a[]){
if (stack_empty(a)==true)
std::cout<<"Underflow"<<"\n";
else{
--top;
return a[top+1];
}
}
void display(int a[]){
for(int i=0;i<=top;i++){
std::cout<<a[i]<<" ";
}
}
int main()
{
**initialise_top();**//this statement initialises top=-1
int arr[7];
//std::cout<<stack_empty(arr)<<"\n";
push(arr,15,7);
push(arr,6,7);
push(arr,2,7);
push(arr,9,7);
push(arr,17,7);
push(arr,3,7);
display(arr);
std::cout<<"\n";
int out=pop(arr);
std::cout<<**out**<<"\n";
return 0;
}
1.In your program the value of top=1 when the first element 15 is inserted. due
to this another value is shown for index 0.
So to have top=0, call the function initialise_top(); in main function.
2.To display 3 instead of 1 use
std::cout<<out<<"\n";
Modifications in the program are bold.
I have tried to improve my code. Please tell me if can improve.
#include <iostream>
#define max 1000
class Stack{
int top;
public:
int a[max];
Stack(){
top=-1;
}
bool stack_empty();
void push(int x);
int pop();
void display();
};
bool Stack::stack_empty(){
if(top==-1)
return true;
else
return false;
}
void Stack::push(int x){
int s=max-1;
if(top<s){
top=top+1;
a[top]=x;
}
else
std::cout<<"overflow"<<"\n";
}
int Stack::pop(){
if (stack_empty()==true)
std::cout<<"Underflow"<<"\n";
else{
--top;
return a[top+1];
}
}
void Stack::display(){
for(int i=0;i<=top;i++){
std::cout<<a[i]<<" ";
}
}
int main()
{
Stack stack1;
stack1.push(15);
stack1.push(6);
stack1.push(2);
stack1.push(9);
stack1.push(3);
stack1.display();
std::cout<<"\n";
std::cout<<stack1.pop()<<"\n";
stack1.display();
return 0;
}

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.

C++ Double free or corruption Error when I believe I'm only freeing once

I'm having an issue with the last function in my code that destroys the array, I keep getting Double free or corruption which I think means I'm freeing it up twice but I can't figure out how i'm doing that
Main Code
#include "terrible_dynamic_size_array_unsorted.h"
using namespace std;
int main()
{
int_array arraytest;
init(arraytest);
if(arraytest.count==0)
{
cout<<"Empty array created"<<endl;
}
else
{
cout<<"Error in array creation"<<endl;
}
clear(arraytest);
if(arraytest.count==0)
{
cout<<"Array cleared of data"<<endl;
}
else
{
cout<<"Error in clear function"<<endl;
}
for(unsigned int i=0;i<25;i+=2)
{
if(arraytest.count < arraytest.DEFAULT_CAPACITY)
{
add(arraytest,i);
print(arraytest);
}
else
{
add(arraytest,i);
print(arraytest);
}
}
for(unsigned int i=1;i<25;i+=2)
{
if(arraytest.count < arraytest.DEFAULT_CAPACITY)
{
add(arraytest,i);
print(arraytest);
}
else
{
add(arraytest,i);
print(arraytest);
}
}
if(arraytest.capacity == 2*arraytest.DEFAULT_CAPACITY)
{
cout<<"Resize function works properly"<<endl;
}
else
{
cout<<"Resize not working properly"<<endl;
}
if(contains(arraytest,6))
{
cout<<"Number 6 present in Array"<<endl;
}
else
{
cout<<"Number 6 not in Array Contains not working properly"<<endl;
}
if(contains(arraytest,30))
{
cout<<"Number 30 present in Array Contains not working properly"<<endl;
}
else
{
cout<<"Number 30 not in Array"<<endl;
}
if(remove(arraytest,23) && arraytest.count == 24)
{
cout<<"Number 23 removed from Array"<<endl;
}
else
{
cout << arraytest.count << endl;
cout<<"Number 23 not in Array error in remove"<<endl;
}
if(remove(arraytest,24) && arraytest.count == 23)
{
cout<<"Number 24 removed from Array"<<endl;
}
else
{
cout<<"Number 24 not in Array error in remove"<<endl;
}
if(remove(arraytest,0) && arraytest.count == 22)
{
cout<<"Number 0 removed from Array"<<endl;
}
else
{
cout<<"Number 0 not in Array error in remove"<<endl;
}
if(remove(arraytest,35))
{
cout<<"Error in remove function"<<endl;
}
else
{
cout<<"Number not in Array"<<endl;
}
destr(arraytest);
if(*arraytest.data == 0)
{
cout<<"Array destroyed"<<endl;
}
else
{
cout<<"Error in destroy"<<endl;
}
return 0;
}
Function code
#include "terrible_dynamic_size_array_unsorted.h"
using namespace std;
void init(int_array& arr)
{
arr.count = 0; //set count to 0
arr.capacity = arr.DEFAULT_CAPACITY;
arr.data = new int[arr.capacity];
}
void clear(int_array& arr)
{
destr(arr); //destroys array
init(arr); // initializes array
}
void destr(int_array& arr) //function for destroying array
{
delete[] arr.data;
//*arr.data = 0;
arr.count = 0;
}
void print(const int_array& arr) //prints out the array
{
for (unsigned int i = 0; i < arr.count; ++i)
cout << arr.data[i] << " ";
cout << endl;
}
bool contains(const int_array& arr, const int& target) //
{
unsigned int i;
for (i = 0; i < arr.count; ++i)
{
if (arr.data[i] == target) return true;
//else return false;
}
return false;
}
void resize(int_array& arr) //resizes the array --- WORKING
{
arr.capacity *= 2;
int* new_data = new int[arr.capacity];
for (unsigned int i = 0; i < arr.count; ++i)
{
new_data[i] = arr.data[i];
}
arr.data = new_data;
delete [] arr.data;
}
void add(int_array& arr, const int& payload)
{
if ((arr.count == arr.capacity))
resize(arr);
arr.data[++arr.count] = payload;
}
bool remove(int_array& arr, const int& target)
{
unsigned int i = 0;
if (arr.count == 0)
{
return false;
}
while (i <= arr.count && arr.data[i] != target) {i++;}
if (i > arr.count)
{
return false;
}
arr.data[i] = arr.data[arr.count];
arr.count--;
return true;
}
Header file
#include <iostream>
struct int_array {
int* data;
unsigned int count;
unsigned int capacity;
static const unsigned int DEFAULT_CAPACITY = 20;
};
void init(int_array& arr);
void destr(int_array& arr);
void resize(int_array& arr);
void clear(int_array& arr);
void add(int_array& arr, const int& payload);
bool contains(const int_array& arr, const int& target);
bool remove(int_array& arr, const int& target);
void print(const int_array& arr);
The problem lies with the function void destr(int_array& arr)
Thank you.
arr.data = new_data;
delete [] arr.data;
should be
delete[] arr.data;
arr.data = new_data;
Or, the old array will be leaked and arr.data will point to already freed memory - which will then be illegally freed again by destr.

C++ program runs in linux but not windows

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.

C++ skipping functions [duplicate]

This question already has answers here:
Calling a function in main
(4 answers)
Closed 4 years ago.
Okay, I think I fixed most of this, but it doesn't like me passing the constants I think. Any help would be greatly appreciated, thank you.
also, with the !inputFile part, I'm not sure how to pull off a return (EXIT_FAILURE) like my teacher suggested..
Also, as to your suggestion with only using one part of the array, would that still allow me to use the whole thing in the function?
The program is supposed to take a file like this:
ex:
NOT 11010001
and it's supposed to read the command as a string, read the binary in as an array, then perform the command on the binary.
The code here is only main function, just don't want to send a wall of it all at once, if this looks okay, then I will happily add the rest. Also, the void Operate () function pretty much calls all of the other functions in one way or another... I'm not sure if that's what's causing it or what. The print table only cout's a table to put all of the info on.
and they headers are wonky for me on here, so just assume those are right.
/* ========================================================================== */
/* Prototypes */
int Power (int, int);
int ReadFile (ifstream inputFile);
void Operate (const int, ifstream&, string, int, int, int);
void CommandNot (const int, int, int);
void CommandAnd (const int, int, int, int);
void CommandOr (const int, int, int, int);
int CommandConvert (const int, int, int);
void CommandLshift (const int, int, int, int);
void PrintTable ();
void PrintOperand (const int &, int);
int main ()
{
//Constants
const int BIT_SIZE = 8;
//Variables
string fileName = "binaryData.txt";
int operandOne [BIT_SIZE];
int operandTwo [BIT_SIZE];
int operandResult [BIT_SIZE];
ifstream inputFile;
PrintTable ();
Operate (BIT_SIZE, inputFile, fileName, operandOne[BIT_SIZE], operandTwo[BIT_SIZE], operandResult[BIT_SIZE]);
return 0;
}
void PrintTable ()
{
cout << "=================================================" << endl;
cout << "= Eight Bit Binary Number Manipulator =" << endl;
cout << "=================================================" << endl << endl;
cout << setw(14) << "COMMAND" << "Operand #1" << "Operand #2" << "Shift" << "Result" << endl;
cout << "----------------------------------------------------------------------" << endl;
}
void Operate (const int BIT_SIZE, ifstream& inputFile, string fileName, int operandOne[], int operandTwo[], int operandResult[])
{
//Variables
int count, shift;
char myChar;
string command;
const int SIZE = BIT_SIZE; //rename constant
inputFile.open (fileName);
if ( !inputFile ) //Check if file opened sucessfully
{
cout << "Error: Data file could not be opened" << endl;
}
while (inputFile) //Read file, and apply commands
{
inputFile >> command;
cout << command << endl;
for ( count = 0; count < SIZE; count++ )
{
inputFile >> myChar;
operandOne[count] = myChar - '0';
}
if (command == "NOT")
{
CommandNot (BIT_SIZE, operandOne[BIT_SIZE], operandResult[BIT_SIZE]);
PrintOperand (BIT_SIZE, operandResult[BIT_SIZE]);
}
else if (command == "AND")
{
count = 0;
for ( count = 0; count < SIZE; count++ )
{
inputFile >> myChar;
operandTwo[count] = myChar - '0';
}
CommandAnd (BIT_SIZE, operandOne[BIT_SIZE], operandTwo[BIT_SIZE], operandResult[BIT_SIZE]);
PrintOperand (BIT_SIZE, operandResult[BIT_SIZE]);
}
else if (command == "OR")
{
count = 0;
for ( count = 0; count < SIZE; count++ )
{
inputFile >> myChar;
operandTwo[count] = myChar - '0';
}
CommandOr (BIT_SIZE, operandOne[BIT_SIZE], operandTwo[BIT_SIZE], operandResult[BIT_SIZE]);
PrintOperand (BIT_SIZE, operandResult[BIT_SIZE]);
}
else if (command == "CONVERT")
{
CommandConvert (BIT_SIZE, operandOne[BIT_SIZE], operandResult[BIT_SIZE]);
PrintOperand (BIT_SIZE, operandResult[BIT_SIZE]);
}
else if (command == "LSHIFT")
{
inputFile >> shift;
CommandLshift (BIT_SIZE, operandOne[BIT_SIZE], operandResult[BIT_SIZE], shift);
PrintOperand (BIT_SIZE, operandResult[BIT_SIZE]);
}
else
{
command = "INVALID";
PrintOperand (BIT_SIZE, operandOne[BIT_SIZE]);
cout << "--- ERROR! Invalid Command ---";
}
}
inputFile.clear();
inputFile.close();
return ;
}
void CommandNot (const int BIT_SIZE, int operandOne[], int operandResult[])
{
int count;
const int SIZE = BIT_SIZE;
for ( count = 0; count < SIZE; count++ )
{
if (operandOne[count] == 0)
{
operandResult[count] = 1;
}
else
{
operandResult[count] = 0;
}
}
}
void CommandAnd (const int BIT_SIZE, int operandOne[], int operandTwo[], int operandResult[])
{
int count;
const int SIZE = BIT_SIZE;
for ( count = 0; count < SIZE; count++ )
{
if ((operandOne[count] == 1) && (operandTwo[count] == 1))
{
operandResult[count] = 1;
}
else
{
operandResult[count] = 0;
}
}
}
void CommandOr (const int BIT_SIZE, int operandOne[], int operandTwo[], int operandResult[])
{
int count;
const int SIZE = BIT_SIZE;
for ( count = 0; count < SIZE; count++ )
{
if ((operandOne[count] == 0) && (operandTwo[count] == 0))
{
operandResult[count] = 0;
}
else
{
operandResult[count] = 1;
}
}
}
int CommandConvert (const int BIT_SIZE, int operandOne[])
{
int count;
const int SIZE = BIT_SIZE;
int baseTenResult = 0;
int place;
for ( count = 0; count < SIZE; count++ )
{
place = SIZE - (count + 1);
if (operandOne[count] == 1)
{
baseTenResult = baseTenResult + Power (2, place);
}
else
{
continue;
}
}
return baseTenResult;
}
void CommandLshift (const int BIT_SIZE, int operandOne[], int operandResult[], int shift)
{
int count;
const int SIZE = BIT_SIZE;
int shiftStart = SIZE - shift;
for ( count = 0; count < SIZE-shift; count++ )
{
operandResult[count] = operandOne[count + shift];
}
for ( count = SIZE - shift; count < SIZE; count++ )
{
operandResult[count] = 0;
}
}
int Power (int base, int power)
{
int count;
int result = 1;
for ( count = 0; count < power; count++ )
{
result = result * base;
}
return result;
}
void PrintOperand (const int BIT_SIZE, int operandResult[])
{
int count;
const int SIZE = BIT_SIZE;
for ( count = 0; count < SIZE; count++ )
{
cout << operandResult[count];
}
}
You need to call the functions from main. You can't do this by sort-of redeclaring them:
void PrintTable();
void Operate (const int BIT_SIZE, ifstream& inputFile, string fileName, int operandOne[], int operandTwo[], int operandResult[]);
Instead, you need to call them:
PrintTable();
Operate(BITSIZE,inputFile,fileName,operandOne,operandTwo,operandResult);
Note, however that there is another problem: Operate requires three integer arguments at the end, but you seem to try to use integer arrays as arguments. You'll need to select one element of each array and submit only that as argument.
(EDIT) A few things have changed in your question, and I don't understand enough to tell what the best overall structure for your data and functions should be, but if you are dealing with integer arrays and you'd like to pass an entire array to a function, you can do it in this way (I've simplified it to a function that takes only one array of integers. Of course you can have more than one function argument):
#include <iostream>
const int SIZE = 3;
/* This is a simpified version of 'operate'. It
takes one argument, which is an array of integers. */
void operate(int a[])
{
/* The only thing I do is to iterate through
all elements of the array and print them. */
int i = 0;
while (i < SIZE) {
std::cout << a[i] << std::endl;
++i;
}
/* IMPORTANT: The length of the array is defined by a
global constant SIZE. Alternatively, you can pass
along the size of the array as a separate argument
to the function. */
}
int main()
{
/* Main program. Here is our array: */
int my_array[SIZE] = { 1,2,3 };
/* And here we call our function: */
operate(my_array);
return 0;
}
However, all of this is a bit complicated and not really as conventient as you could have it in C++ (as opposed to C). In all likelihood, you'll be much better of not using arrays at all, and replacing them with std::vector. Best check on cppreference for examples of how to use it (also click on some of the member functions, such as the constructor and push_back to get specific code examples.)