Getting garbage value when trying to get the value from Private Array - c++

I have created a class called Array in which there is a static Array . I have made this Array as private.
class Array
{
private:
int A[10] ;
int size;
int length;
I want to access the value of the elements of this array. For this I have created one get function which would return the values of elements at different positions.
int Array::Get(int x)
{
return A[x];
}
But when I try to print the value of the particular element after inserting elements in array it throws some garbage value.
Full CODE:
#include <iostream>
using namespace std;
class Array
{
private:
int A[10] ;
int size;
int length;
public:
Array()
{
A[10];
size =10;
length = 0;
}
Array(int sz)
{
int A[10];
size = sz;
length = 0;
}
void Display();
void Append(int x);
int Get(int x);
};
int Array::Get(int x)
{
return A[x];
}
void Array::Display ()
{
cout << "\n Elements are\n";
for (int i = 0 ; i < length ; i++)
{
cout<<A[i]<<" ";
}
}
void Array::Append(int x)
{
if(length<size)
A[length++]=x;
}
int main()
{
Array arr1;
int si = 10;
arr1= Array(si);
cout << "enter the elements here" << endl;
int x;
for (int i = 0 ; i < si ; i++)
{
printf("enter the element %d \n " , i);
scanf("%d",&x);
arr1.Append(x);
}
arr1.Display() ;
int count;
count = arr1.Get(0);
printf("%d" , &count);
}

I assume you are a c developer or used to use c.
Thanks guys for pointing out bad lines in your code.
I tried your code in my IDE and fixed it, but I think you need to study more in the classes. I am a beginner but I noticed these mistakes in your code.
First, when you want to create an array of flexible size, you should not give it a fixed size.
As you did in your class member variables:
private:
int A[10] ;
int size;
int length;
You already gave it a size of 10, but in the constructors you created a constructor that tries to resize the array:
Array(int sz)
{
int A[10];
size = sz;
length = 0;
}
Also when you try to get the number x of your array:
int number;
count = arr1.Get(0);
printf("%d" , &count);
You are specifying the address of the variable count, not its value.
Here is your fixed code :
#include <iostream>
using namespace std;
class Array {
private:
int *A;
int size;
int length;
public:
Array() {
// default constructor
A = new int[10];
size = 10;
length = 0;
}
Array(int sz) {
// change the size of array
size = sz;
A = new int[sz];
length = 0;
}
~Array(){
delete [] A;
}
void Display();
void Append(int x);
int Get(int x);
};
int Array::Get(int x) {
if (x < length)
return A[x];
else {
std::cerr << "number is out of rang\n\a";
return 0;
}
}
void Array::Display() {
cout << "\n Elements are\n";
for (int i = 0; i < length; i++) {
cout << A[i] << " ";
}
}
void Array::Append(int x) {
if (length < size)
A[length++] = x;
}
int main() {
int si;
// changing size
// int newsize;
// std::cout << "enter size of your array : ";
// std::cin >> newsize;
// si = newsize;
// Array arr2(newsize);
// default constructor with size 10
Array arr1;
si = 10;
// no need to this
// arr1= Array(si);
cout << "enter the elements here" << endl;
int x;
for (int i = 0; i < si; i++) {
std::cout << "enter number " << i + 1 << " : ";
std::cin >> x;
arr1.Append(x);
}
arr1.Display();
int chose;
std::cout << "enter number to find in array : ";
std::cin >> chose;
int num = arr1.Get(chose);
// if chose is not out of array range
if (num)
std::cout << "number " << chose << " in array is : " << num << '\n';
}

Related

Can't manage to display the last array

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)

Why my C++ programme has stopped working?

I wrote C++ programme in vs code and When I run it, it ask me to enter the element value but when I enter the second time, it has stopped working. I don't know what the problem is but if you know the please help me to resolve the problem.
#include <iostream>
using namespace std;
class myArray {
public:
int total_size;
int used_size;
int* ptr;
myArray(int tsize, int usize)
{
total_size = tsize;
used_size = usize;
ptr = new int(tsize);
}
myArray() {}
void setvalue()
{
int n;
for (int i = 0; i < used_size; i++) {
cout << "Enter the element" << endl;
cin >> n;
ptr[i] = n;
}
}
void show()
{
for (int i = 0; i < used_size; i++) {
cout << "The element in array" << endl;
cout << ptr[i] << endl;
}
}
};
int main()
{
myArray(10, 2);
myArray a;
a.setvalue();
a.show();
return 0;
}
You used used_size and ptr without initializing them in a.setvalue(); and a.show();.
It seems
myArray(10, 2);
myArray a;
should be
myArray a(10, 2);
Also, as #Yksisarvinen points out,
ptr = new int(tsize);
should be
ptr = new int[tsize];
to allocate an array instead of single int.

Dynamically allocated

I need help, to change the size and arr, in the main function to allocate memory dynamically (dynamically allocated)
this program uses looping for integer numbers for the 1st program, while classes and structs are the second program
program_1
#include <iostream>
#include <iterator>
using namespace std;
void display_desc(const int arr[], int size)
{
int copy_arr[size];
copy(arr, arr + size, copy_arr);
int temp;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (copy_arr[i] > copy_arr[j]) {
temp = copy_arr[i];
copy_arr[i] = copy_arr[j];
copy_arr[j] = temp;
}
}
}
for (int i = 0; i < size; i++) {
cout << copy_arr[i] << " ";
}
cout << endl;
}
int main()
{
int size = 5;
int arr[size];
for (int i = 0; i < size; i++) {
arr[i] = i;
}
display_desc(arr, size);
}
and
program_2
Change the variable that is in int main () to use dynamic memory allocation
#include <iostream>
#include <iterator>
#include <windows.h>
using namespace std;
const int SLOT_ROOM = 5;
class Person {
public:
Person()
{
name = "";
}
Person(string names)
{
name = names;
}
void set_name(string names) { name = names; }
string get_name() { return name; }
private:
string name;
};
struct Slot {
bool blank;
Person person;
};
class rental {
public:
Slot used[SLOT_ROOM];
rental()
{
for (int i = 0; i < SLOT_ROOM; i++) {
Person person;
used[i].person = person;
used[i].blank = true;
}
}
int in(const Person person)
{
for (int i = 0; i < SLOT_ROOM; i++) {
if (used[i].blank) {
used[i].blank = false;
used[i].person = person;
cout << "used in position " << i << endl;
return i;
}
}
cout << "the rental is full" << endl;
return -1;
}
bool out(int i)
{
used[i].blank = true;
}
Slot* get_rental_list()
{
return used;
}
void print_person_list()
{
cout << endl
<< "List rental" << endl;
for (int i = 0; i < SLOT_ROOM; i++) {
cout << "Slot rental to " << i << endl;
cout << "Name: " << used[i].person.get_name() << endl;
cout << "Avail: " << used[i].blank << endl
<< endl;
}
}
private:
int SLOT_ROOM = 2;
string time_rental;
};
int main()
{
rental rental;
Person person_1("make");
Person person_2("angel");
rental.in(person_1);
rental.in(person_2);
rental.print_person_list();
rental.out(2);
rental.print_person_list();
rental.in(person_2);
rental.print_person_list();
}
please help, I don't understand about using dynamic memory allocation
I still learn c ++
Change
int arr[size];
to
int* arr = new int[size];
You need to make the same change to int copy_arr[size]; in display_desc.
You also need to delete[] memory once you've finished with it.
delete[] arr;
at the end of main, and delete[] copy_arr; at the end of display_desc.
In the second question it's harder to understand what you want. Why do you want to use dynamic allocation? Your code looks perfectly good as it is. You also don't say which variable it is that you want to use dynamic allocation.

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;
}