Can't manage to display the last array - c++

I have these code:
#include<iostream>
#include<iomanip>
using namespace std;
class Array {
private:
static const int size = 100;
int arr[size];
public:
Array();
void display();
Array& operator+(const Array& arr);
};
Array::Array()
{
for (int i = 0; i < size; i++)
{
arr[i] = rand() % 99 + 1;
}
}
void Array::display()
{
for (int i = 0; i < size; i++)
{
cout << setw(5) << arr[i];
if ((i + 1) % 10 == 0)
cout << endl;
}
}
Array & Array::operator+(const Array & arr)
{
Array temp;
for (int i = 0; i < size; i++)
{
temp.arr[i] = this->arr[i] + arr.arr[i];
}
return temp;
}
int main()
{
srand(time(NULL));
Array arr1, arr2;
cout << "arreglo 1:\n";
arr1.display();
cout << endl;
cout << "arreglo 2:\n";
arr2.display();
cout << endl;
//adding both arr HERE IS MY PROBLEM
Array arr3 = arr1 + arr2;
cout << "Suma de arreglo 1 y arreglo 2: " << endl;
arr3.display();
cout << endl;
return 0;
}
Somehow it can't manage to display Array arr3 = arr1 + arr2.

Array & Array::operator+(const Array & arr)
{
Array temp;
...
return temp;
}
This returns a reference to an object that goes out of scope and is destroyed after the function returns. As a general rule you should not return addresses of or references to local variables.
Remove the & so it returns a new Array instead:
Array Array::operator+(const Array & arr)

Related

OOP C++ language

I started learning OOP in C++. I try to solve a task like this:
Create a class - a list based on a one-size-fits-all array of integers. Assign a constructor, a destructor, the functions of adding an element to the top (end) of the list, selecting an element from the list by number, sorting the list, showing the elements of the list to the top and to the bottom of the list."
In the delete function, the compiler constantly knocks out the same error:
E0852 the expression must be a pointer to the full type of the object My_4_Project C:\Users\artem\source\repos\Project4\My_4_Project\Source.cpp
Here is my code:
#include <iostream>
#include <algorithm>
using namespace std;
class Array {
private:
int* a;
unsigned int size;
int b, c = 0, d;
public:
Array();
Array(int s);
~Array();
int& operator[](int index);
void setarray();
void getarray();
void add();
void delet();
void sort();
};
Array::Array() {
size = 10;
a = new int[size];
for (size_t i = 0; i != size; i++) {
a[i] = 0;
}
}
Array::Array(int s) {
if (s > 0) {
size = s;
a = new int[size];
for (size_t i = 0; i != size; i++) {
a[i] = 0;
}
}
else cout << "Size can't be negativ";
}
Array::~Array() {
delete[]a;
}
int& Array::operator[](int index) {
if (index <= size) {
return a[index];
}
}
void Array::setarray() {
for (size_t i = 0; i != size; i++) {
cin >> a[i];
}
}
void Array::getarray() {
for (size_t i = 0; i != size; i++) {
cout << a[i] << " ";
}
}
void Array::add()
{
/* ? ? ? */ ;
}
void Array::delet() {
cin >> b;
for (int i = 0; i < size; i++)
{
if (b == a[i])
c++;
if (c > 2) delete a[i];
}
cout << c;
}
void Array::sort() {
int temp;
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
for (int i = 0; i < size; i++) {
cout << a[i] << " ";
}
}
int main() {
cout << "Enter 10 number`s massive: ";
Array arr(10);
arr.setarray();
cout << endl;
arr.getarray();
cout << endl;
cout << "Sorted massive: ";
arr.sort();
cout << endl;
cout << "Witch symbol you wanna delete?: ";
arr.delet();
return 0;
}
The problem is that delete does not work as you think:
You can delete an object that you previously created with new (new returns a pointer, and delete expect that same pointer).
You can delete[] something that you previously created with new[]
But no mixing: you cannot delete an individual element when it was part of an array created with new[]
I will not do the exercise for you but the trick is to:
find the index of the duplicate element you want to get rid off,
copy every elements afterwards to one index before (i.e. a[j]=a[j+1], of course, making sure that j+1<size )
reduce the size by one.
So something like:
void Array::delet() {
cin >> b; // better put this in main() and pass it as argument
for (int i = 0; i < size; i++)
{
if (b == a[i])
{ // it'll be more than a single statement
c++;
if (c > 2) // found a duplicate
{ // NO delete a[i];
... // insert a loop to copy the next ones
// and reduce the size
... // EXTRA CAUTION: in this case the next element
// is again at offset i and not i++
}
}
}
cout << c; // ok, you can display the number of occurences counted
}

Copying data in a simple vector class

I'm trying write my own vector class:
template <typename T>
class Vector {
public:
Vector(int default_size = 2) :
size(0), data_member(new T[default_size]), capacity(default_size) {};
Vector(const Vector& obj)
{
data_member = new T[obj.size];
data_member = obj.data_member;
size = obj.size;
capacity = obj.capacity;
}
void push_back(T& elem)
{
if (size == capacity)
resize(2 * size);
data_member[size] = elem;
size++;
}
void push_front(T& data)
{
if (size + 1 == capacity)
resize(2 * size);
for (int i = size - 1; i >= 0; i--)
{
data_member[i + 1] = data_member[i];
}
data_member[0] = data;
size++;
}
void pop_back()
{
--size;
}
void resize(int size_)
{
if (size_ > capacity)
{
T* temp = new T[size_];
memcpy(temp, data_member, size * sizeof(T));
delete[] data_member;
data_member = new T[size_];
data_member = temp;
//delete[] temp;
capacity = size_;
}
}
int get_size() { return size; }
T* getarr() { return data_member; }
private:
T* data_member;
int size;
int capacity;
};
and here is a main for testing my class
int main()
{
Vector<int> myint;
int a = 5, b = 8, c = 9;
myint.push_back(a);
myint.push_back(b);
myint.push_back(c);
Vector<int> you = myint;
int* arr1 = you.getarr();
for (int i = 0; i < you.get_size(); i++)
{
cout << *arr1 << endl;
arr1++;
}
cout << endl << endl;
int h[3] = { 1,2,3 };
int* hp = h;
int g[3] = { 4,5,6 };
int* gp = g;
int f[3] = { 4,5,6 };
int* fp = f;
Vector<int*> myarrint;
myarrint.push_back(hp);
myarrint.push_back(gp);
myarrint.push_back(fp);
int** arr = myarrint.getarr();
for (int i = 0; i < myarrint.get_size(); i++)
{
for (int j = 0; j < 3; j++)
{
cout << **arr << endl;
(*arr)++;
}
arr++;
}
cout << endl << endl;
Vector<string> mystr;
string s1 = "I";
string s2 = "went";
string s3 = "shopping";
mystr.push_back(s1);
mystr.push_back(s2);
mystr.push_back(s3);
string* str1 = mystr.getarr();
for (int i = 0; i < mystr.get_size(); i++)
{
cout << *str1 << endl;
str1++;
}
cout << endl << endl;
string i = "wow";
mystr.push_front(i);
string* str2 = mystr.getarr();
for (int i = 0; i < mystr.get_size(); i++)
{
cout << *str2 << endl;
str2++;
}
cout << endl << endl;
return 0;
}
I'm new in c++ and I'm really confused, I think in my push_back function, I'm just making my objects point to temp and I'm not copying temp in them , so if I want to delete temp in the end of my push_back function my data_members will be lost. So what is the right way to do so?
second if I want to make a dynamic array of strings my program will crash sometimes, and I think ,it's because of memcpy() in my resize function, still I don't know what should I do instead of it?

How to access elements of the array just by having the array's memory location? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
So, this is just few methods from my myArray.cpp class. It gives me error on
setSize(orig.getsize());
for(int i = 0; i<getSize();i++)
setData(i,orig.getData(i));
these above code(error - which is non-class type double). can anyone please help me? I'm trying to copy an array to the object array
myArray::myArray(double* orig, int size) {
setSize(orig.getsize());
for(int i = 0; i<getSize();i++)
setData(i,orig.getData(i));
}
void myArray::setSize(int value) {
if (value > 0) {
size = value;
}
}
void myArray::setData(int index, double value) {
if ((index >= 0) && (index < size)) {
arr[index] = value;
} else {
// cout << "NO!" << endl;
}
}
double myArray::getData(int index) const {
if ((index >= 0) && (index < size)) {
return arr[index];
} else {
return arr[size - 1];
}
}
That's my main.cpp class
#include <iostream>
#include "myArray.h"
//#include "myArray.cpp"
using namespace std;
int main (int argc, char **argv)
{
cout << "**************Testing Default Constructor*****************" << endl;
myArray A1;
cout << "A1: ";
A1.print();
cout << "**************Testing Alt Constructor 1*****************" << endl;
myArray A2(5,0);
cout << "A2: ";
A2.print();
cout << "**************Testing init*****************" << endl;
A2.init();
cout << "A2 after init: ";
A2.print();
int size = 5;
double *temp = new double[size];
for(int i = 0; i < size; i++)
{
temp[i] = i;
}
cout << "**************Testing Alt Constructor 2*****************" << endl;
myArray A3(temp, size);
cout << "A3: ";
cout << A3.getSize();
cout << endl;
cout << "Fe";
A3.print();
That's my myArray.cpp class
#ifndef MYARRAY_H_INCLUDED
#define MYARRAY_H_INCLUDED
/***************************************************************************
* myArray class header file
***************************************************************************/
class myArray
{
public:
myArray();
myArray(int,double);
myArray(double*, int);
~myArray();
int getSize() const;
bool equal(const myArray &rhs) const;
void setData(int index, double value);
void insert(int, double);
void remove(int);
double get(int);
void clear();
int find(double);
bool equals(myArray&);
void print() const;
void init();
double getData(int index) const;
// void init();
// void print() const;
void expand();
private:
int size;
double *arr;
void setSize(int value);
};
#endif // MYARRAY_H_INCLUDED
That's my myArray.cpp class where I'm getting the error in the default paramaterized constructor
#include "myArray.h"
#include <iostream>
using namespace std;
myArray::myArray() : size(0) {
// size = 10;
arr = new double [size];
}
/*myArray::myArray(int _size) : size(_size) {
// size = _size;
arr = new double [size];
for (int i = 0; i < size; i++) {
arr[i] = i;
}
} */
myArray::myArray(int _size, double value) : size(_size) {
// size = _size;
arr = new double [size];
for (int i = 0; i < size; i++) {
arr[i] = value;
}
}
/*myArray::myArray(myArray* temp, int size)
{
setSize(temp.getSize());
for (int i = 0; i < getSize(); i++) {
setData(i, temp.getData(i));
}
} */
myArray::myArray(double* orig, int size) {
setSize(orig.getsize());
for(int i = 0; i<getSize();i++)
setData(i,orig.getData(i));
//double arr[size];
// arr = new double[size];
// p = orig;
// for(int i = 0;i<size;i++)
// {
// arr[i] = orig[i];
// cout << arr[i] << " ";
// }
// cout << endl;
// setSize(size);
// for (int i = 0; i < getSize(); i++)
// setData(i, orig.getData(i));
// cout << "hell";
// for (int i = 0; i < size; i++) {
// arr[i] = myArray[i];
// cout << arr[i];
//}
// arr = myArray;
}
myArray::~myArray() {
delete [] arr;
}
int myArray::getSize() const {
return size;
}
void myArray::setSize(int value) {
if (value > 0) {
size = value;
}
}
void myArray::setData(int index, double value) {
if ((index >= 0) && (index < size)) {
arr[index] = value;
} else {
// cout << "NO!" << endl;
}
}
double myArray::getData(int index) const {
if ((index >= 0) && (index < size)) {
return arr[index];
} else {
return arr[size - 1];
}
}
void myArray::print() const {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
void myArray::expand() {
double *localArray = new double[size + 1];
for (int i = 0; i < size; i++) {
localArray[i] = arr[i];
}
localArray[size] = size;
delete [] arr;
setSize(size + 1);
arr = localArray;
// myArray = new int[size];
//
// //Is this a deep-copy or a shallow-copy?
// //Can you replace one with the other?
// //What are the advantages and disadvantages?
// for(int i=0; i < size; i++) {
// myArray[i] = localArray[i];
// }
// delete [] localArray;
}
bool myArray::equal(const myArray& rhs) const {
bool result(true);
if (getSize() != rhs.getSize()) {
result = false;
} else {
for (int i = 0; i < getSize(); i++) {
if (getData(i) != rhs.getData(i)) {
result = false;
}
}
}
return result;
}
void myArray::init()
{
cout << "Enter the " << size << " elements to populate the array " << endl;
for(int i = 0;i<getSize();i++)
{
int value;
cin >> value;
setData(i,value);
}
}
Sorry I somehow I thought you wanted help with a runtime error but you want help with the compile errors.
The compile error in this part of the code
myArray::myArray(double* orig, int size) {
setSize(orig.getsize());
for(int i = 0; i<getSize();i++)
setData(i,orig.getData(i));
is specifically about the orig.getSize() part. orig is of type double* (pointer to double) and pointers do not have member functions only classes do which is why the compiler says: "which is non-class type double"
Actually there is no way in c++ to know from a pointer to how many elements it points but luckily your function already has a parameter size which i guess is meant to pass in the size of the orig array. So that line should be setSize(size);
Now two lines lower you get a similar error on setData(i,orig.getData(i)); orig is still a double* so it still doesn't have member functions. The correct way is setData(i, orig[i]);
EDIT:
BTW, i quick look through the rest of your code shows me that your setSize method doesn't allocate an array of appropriate size so you should fix that to.

Inputting the amount you want displayed in the array

I am writing a program that displays integer arrays. I set the size of the array, but I am wondering how I can ask the user the index of the array that they want listed. Say the const SIZE = 10, and the user wants to see the first three in the array. I want to also write an exception that catches the error if the user input is over the size of the array. If you need to see some code, let me know. Any help is appreciated!
intergerarray.h
class IntArray
{
private:
int *aptr; // Pointer to the array
int arraySize; // Holds the array size
void subscriptError(); // Handles invalid subscripts
public:
class OutOfBoundException
{
public:
int index;
OutOfBoundException(){};
int getInde() { return index; }
};
IntArray(int); // Constructor
IntArray(const IntArray &); // Copy constructor
~IntArray(); // Destructor
int size() const // Returns the array size
{
return arraySize;
}
int &operator[](const int &); // Overloaded [] operator
};
IntergerArray.cpp
IntArray::IntArray(int s)
{
arraySize = s;
aptr = new int[s];
for (int count = 0; count < arraySize; count++)
*(aptr + count) = 0;
}
IntArray::IntArray(const IntArray &obj)
{
arraySize = obj.arraySize;
aptr = new int[arraySize];
for (int count = 0; count < arraySize; count++)
*(aptr + count) = *(obj.aptr + count);
}
IntArray::~IntArray()
{
if (arraySize > 0)
delete[] aptr;
}
void IntArray::subscriptError()
{
cout << "ERROR: Subscript out of range.\n";
exit(0);
}
int &IntArray::operator[](const int &sub)
{
if (sub < 0 || sub >= arraySize)
subscriptError();
return aptr[sub];
}
driver file.cpp
int main()
{
int SIZE = 10;
//int index;
//cout << "enter an index";
//cin >> index;
IntArray table(SIZE);
for (int x = 0; x < SIZE; x++)
table[x] = x;
for (int x = 0; x < SIZE; x++)
cout << table[x] << " ";
cout << endl;
//table[SIZE + 1] = 0;
return 0;
}
Isn't this what you are trying to do? why so much code for such a simple problem?
const int arraySize = 10;
int array[arraySize];
int elementToDis;
do
{
std::cout << "Number of array elements to display: ";
std::cin >> elementToDis;
} while (elementToDis > arraySize || elementToDis < 0); // this is your exeption
for (int ccc(0); ccc < elementToDis; ++ccc)
std::cout << "Index " << ccc << ": " << array[ccc] << '\n';
I think you want to display all elements lower than an index value entered by the user :
Let array[] be the array name of size=10,you can get an index value (say l) from the user and use that value inside a for loop for printing all elements in index lower than l
int array[size]
void disp_in(int l)
{
if(l>=size) // if l greater than or equal to size (as index start at 0)
throw l;
else
{
cout<<"Elements : ";
for(int i=0;i<=l;i++) //if we have say l=2 ,array values in indexes 0,1and 2 will be displayed
cout<<array[i];
}
}
int main ()
{
int l;
cout<<"Enter index : ";
cin>>l; //till this index value, the array value will be displayed
try
{
disp_in(l);
}
catch(int e)
{
cout<<"Index value greater than max index";
}
return 0;
}
You could try something like this:
#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>
void print_numbers( const std::vector<int>& array, int nNumbers, const char* pszSeparator )
{
if ( nNumbers > static_cast<int>(array.size()) )
{
throw std::exception();
}
std::copy( array.begin(), array.begin() + nNumbers, std::ostream_iterator<int>( std::cout, pszSeparator ) );
}
int main()
{
std::vector<int> array( 10 );
//Just for testing
{
int n = 0;
auto generator = [n]() mutable
{
return n++;
};
std::generate_n( array.begin(), array.size(), generator );
}
try
{
print_numbers(array, 11, "\n");
}
catch ( std::exception e )
{
std::cout << "Error message..." << std::endl;
}
return 0;
}

C++ HEAP error when delete [] is called

I keep getting the error in VS 2100 "CRT detected that the application wrote to memory before start of heap buffer"
Can anyone help? My int Main is all the way on the bottom. The error occur when the delete [] command is run on the operator= function
#include "intset.h"
const int MAXINITIALSIZE = 5;
int IntSet::numOfArray = 0;
IntSet::IntSet(int a, int b, int c, int d, int e)
{
numOfArray++;
int tempArray[] = {a, b, c, d, e};
size = determineHighest(tempArray) + 1; //determines largest int
cout << "size is " << size << endl;
arrayPtr = new bool[size]; //creates array of bool
for (int i = 0; i < size; i++) //fill bool array
{
arrayPtr[i]= false; //arrayptr is a bool pointer created in the header
}
for (int i = 0; i < MAXINITIALSIZE; i++)
{
arrayPtr[tempArray[i]]= true;
}
for (int i = 0; i < size; i++)
{
cout << &arrayPtr[i] << endl;
}
}
IntSet::IntSet(const IntSet &intsetObject)
{
numOfArray++;
size = intsetObject.size;
arrayPtr = new bool[size];
for (int i = 0; i < size; i++)
{
if (intsetObject.arrayPtr[i])
arrayPtr[i] = intsetObject.arrayPtr[i];
}
}
IntSet::~IntSet()
{
--numOfArray;
delete [] arrayPtr;
arrayPtr = NULL;
}
int IntSet::determineHighest(int tempArray[])
{
int temp = tempArray[0];
for (int i = 1; i < MAXINITIALSIZE; i++)
{
if (tempArray[i] > temp)
temp = tempArray[i];
else
continue;
}
return temp;
}
IntSet& IntSet::operator=(const IntSet &intsetObject) //ask about IntSet&
{
cout << "inside operator=" << endl;
if (&intsetObject != this)
{
for (int i = 0; i < size; i++)
{
cout << &arrayPtr[i] << endl;
}
delete [] arrayPtr; //HEAP ERROR HERE!
for (int i = 0; i < size; i++)
{
cout << &arrayPtr[i] << endl;
}
size = intsetObject.size
arrayPtr = new bool[size]();
for (int i = 0; i < size; i++)
{
if (intsetObject.arrayPtr[i])
arrayPtr[i] = intsetObject.arrayPtr[i];
}
}
return *this;
}
ostream& operator<<(ostream &output, const IntSet &intsetObject)
{
output << "{ ";
for (int i = 0; i < intsetObject.size; i++)
{
if (intsetObject.arrayPtr[i] == true)
{
output << i << " ";
}
else
continue;
}
output << "}";
return output;
}
//main
#include "intset.h"
int main() {
IntSet object2(9);
IntSet object4(3,6);
object4 = object2;
return 0;
}
This can only happen if arrayPtr is accessed with a negative index. I suspect your defaults for a,b,c,d,e are -1 in the declaration for IntSet::IntSet, so it is writing to arrayPtr[-1] in the set-true loop. Check for tempArray[i] >= 0 there.
Also, you can't print the array after you have deleted it, so you should remove those lines after the delete, although they should be "harmless" in that only garbage will be printed, but who knows - the OS could release the page containing the array and it could segfault your program.
Finally, you should not test if (intsetObject.arrayPtr[i]) in the copy & = operators. Otherwise all "false" elements in the source array become uninitialized in the destination array (new bool[size] does not initialize the array to all false).