Dynamically allocated - c++

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.

Related

Getting garbage value when trying to get the value from Private Array

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

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.

Problem using std::sort with custom class

Doing hackerrank problem "Attending Workshops" https://www.hackerrank.com/challenges/attending-workshops/problem
I have the problem that I can't sort my vector. I tried with a lambda (in commentary) and then by overloading the operator >.
My vector never turn out to be sorted. Can you help me find what I did wrong. Here is my code:
#include<bits/stdc++.h>
using namespace std;
//*************ABOVE IS LOCKED CODE BY HACKERRANK****************;
//Define the structs Workshops and Available_Workshops.
//Implement the functions initialize and CalculateMaxWorkshops
struct Workshop
{
int startTime;
int endTime;
int duration;
Workshop(){}
Workshop(int pStartTime, int pDuration)
:startTime(pStartTime), duration(pDuration)
{
endTime = startTime + duration;
}
bool operator < (const Workshop &other) const
{
cout << "trace inside operator never showing up" << endl;
return endTime < other.endTime;
}
};
struct Available_Workshops
{
int nbWorkshop;
vector<Workshop> workshops;
Available_Workshops(int *start_times, int *durations, int n)
:nbWorkshop(n)
{
workshops.reserve(n);
for(int i = 0; i < n; ++i)
{
workshops[i] = Workshop(start_times[i], durations[i]);
}
}
};
Available_Workshops *initialize(int *start_time, int *duration, int n)
{
return new Available_Workshops(start_time, duration, n);
}
int CalculateMaxWorkshops(Available_Workshops *avai_work_ptr)
{
//The two for loops are just there to trace the content of avai_work_ptr->nbWorkshop to validate sorting...
for(int i = 0; i < avai_work_ptr->nbWorkshop; ++i)
cout << avai_work_ptr->workshops[i].startTime << " " << avai_work_ptr->workshops[i].endTime << endl;
std::sort(avai_work_ptr->workshops.begin(), avai_work_ptr->workshops.end());//, [](const Workshop &a, const Workshop &b){cout << "compar"; return a.startTime < b.startTime;});
for(int i = 0; i < avai_work_ptr->nbWorkshop; ++i)
cout << avai_work_ptr->workshops[i].startTime << " " << avai_work_ptr->workshops[i].endTime << endl;
int maxWorkshop = 0;
//Chunk of code removed because it is not related to the sort problem...
//...
return maxWorkshop;
}
//*************BELOW IS LOCKED CODE BY HACKERRANK****************;
int main(int argc, char *argv[]) {
int n; // number of workshops
cin >> n;
// create arrays of unknown size n
int* start_time = new int[n];
int* duration = new int[n];
for(int i=0; i < n; i++){
cin >> start_time[i];
}
for(int i = 0; i < n; i++){
cin >> duration[i];
}
Available_Workshops * ptr;
ptr = initialize(start_time,duration, n);
cout << CalculateMaxWorkshops(ptr) << endl;
return 0;
}
Thank you.
workshops.reserve(n);
is wrong. It just do allocation and not inclease the number of valid elements, so the end() iterator will still be the top of the array.
You should use
workshops.resize(n);
instead.

C++ allocating memory

Can someone explain me why when i back form function i lost my data from tabOfOffsets. I did the same thing twice and program crash only with the second array.
I printed values of this array on the end of function and everything is clear and correct. Maybe i make mistake somewhere with delete?
Below it is the code.
#include<iostream>
#include <algorithm>
using std::cout;
using std::endl;
void changeSizeOfVector(int *tabValue, int *tabOffsets, int &oldSize, int
newSize) {
int temp = std::min(oldSize, newSize);
int *newTabOfValues = new int [newSize] {0};
int *newTabOfOffsets = new int [newSize] {0};
for (int i = 0; i < temp; i++) {
newTabOfValues[i] = tabValue[i];
newTabOfOffsets[i] = tabOffsets[i];
}
delete[] tabValue;
delete[] tabOffsets;
tabValue = new int [newSize] {0};
tabOffsets = new int [newSize] {0};
for (int i = 0; i < newSize; i++) {
tabValue[i] = newTabOfValues[i];
tabOffsets[i] = newTabOfOffsets[i];
std::cout << tabOffsets[i] << tabValue[i] << endl;
}
oldSize = newSize;
delete[] newTabOfValues;
delete[] newTabOfOffsets;
for (int i = 0; i < newSize; i++) {
std::cout << tabOffsets[i] << tabValue[i] << endl;
}
}
int main() {
int SIZE = 10;
int * tabOfOffsets = new int[SIZE];
int * tabOfValues = new int[SIZE];
for (int i = 0; i < SIZE; i++)
{
tabOfValues[i] = i;
tabOfOffsets[i] = i;
cout << tabOfValues[i] << " : " << tabOfOffsets[i] << endl;
}
changeSizeOfVector(tabOfValues, tabOfOffsets, SIZE, 12);
for (int i = 0; i < SIZE; i++) {
cout << tabOfOffsets[i] << " : " << tabOfValues[i] << endl;
}
delete[] tabOfOffsets;
delete[] tabOfValues;
}
This function declaration is wrong:
void changeSizeOfVector(int *tabValue, int *tabOffsets, int &oldSize, int
newSize);
it means you can change the values of tabOffsets but not the pointer itself in order to make it behave correctly you should declare it as follows:
void changeSizeOfVector(int *tabValue, int **tabOffsets, int &oldSize, int
newSize);
This way you can change the pointer itself and assign a newly allocated array to 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.