#include<iostream>
#include<array>
#include <algorithm>
using namespace std;
class Array{
//declaring a array
public: int a[4];
public: int num;
public:
Array() {
//initializing a array
a[0] = 1;
a[1] = 2;
a[2] = 3;
a[3] = 4;
}
Array(const Array &NewObj){
a = new int[4];
for (int i = 0; i < 4; i++)
a[i] = NewObj.a[i];
}
};
int main()
{
cout<<" DEEP COPY : \n";
cout<<"============ \n";
//creating first object
Array obj1;
//changing value of a array at index 3
obj1.a[3]=15;
//declaring second object which is mapped by object 1
Array obj2(obj1);
cout << "Object 1: \n";
//printing values of a array
for(int i=0;i < (sizeof(obj1.a) / sizeof(obj1.a[0])); i++){
cout<<obj1.a[i];
cout << "\n";
}
cout << "Object 2: \n";
for(int i=0;i < (sizeof(obj2.a) / sizeof(obj2.a[0]));i++){
cout<<obj2.a[i];
cout << "\n";
}
return 0;
}
when creating a deep copy of a variable :
a = new int[4];
I received the error: expression must be a modifiable lvalue at this line.
The primary program's purpose is to make a deep copy of an array.
I started by defining the class and declaring an array.
Then I wrote a constructor () { [native code] } that initialises an array.
Then I wrote a copy constructor () { [native code] } in which I built a new array in which the values could be saved, but it failed with an exception about editable values.
You can get rid of a = new int[4]. Think about why you don't need that line in the regular constructor. Do you actually need to be allocating more memory?
Related
Write a function, reverseArray, that when passed an int array of length greater than 0 will return a dynamically allocated array of the same length but with the elements in the reverse order. For example, if passed the array, {1,2,3,4,5,6,7,8,9,0} the function would return the array {0,9,8,7,6,5,4,3,2,1}.
Below is my code, but there is a bug in it.
This is my output.
1
2
3
4
5
6
4113
6
5
4
3
2
1
0x7fffe697ceb0
The 4113 and address are provided by the compiler.
#include <iostream>
using namespace std;
int * readNumbers() {
int * a = new int[6];
for (int i = 0; i < 6; i++) {
int x;
cin >> x;
a[i] = x;
}
// a++;
return a;
delete[] a;
}
int *reverseArray(int *numbers1,int length) {
for (int i = length; i >=0; i--) {
cout << numbers1[i] << endl;
}
return numbers1;
delete [] numbers1;
}
int main() {
int *arr1 = readNumbers();
cout << reverseArray(arr1,6) << endl;
return 0;
}
I think there may have been an issue with your wording. Assuming you want your function just to print the reverse of a passed array, you're off to a good start.
One issue is what was said in the comments: your for loop is indexing past your array. When you type int * a = new int[6]; you are creating a pointer 'a' which points to a location in memory. Since you chose size 6, the appropriate amount of memory is allocated. If you happen to index outside of that range, you will end up pointing to a random spot in memory, not allocated for your array. Hence why you are getting a weird number '4113'.
A fix for this could be:
int i = length changed to int i = length-1
Another issue is that your function returns an integer pointer, and you are trying to cout this pointer. As another commenter said, you have to think about what this does. If you try this code:
#include <iostream>
using namespace std;
int main() {
int arr[] = {1, 2, 3};
cout << arr << endl;
return 0;
}
your output would be something like 0xff09ba. This represents the location of the start of the array in memory. If you change arr to (arr + 1) you will get the location of the second index of the array.
So when you type cout << reverseArray(arr1,6) << endl; you are really just printing out the location of numbers1 in memory. This is why you are getting '0x7fffe697ceb0' in your output. To fix this, simply make your function
void reverseArray(int *numbers1,int length) {
for (int i = length; i >=0; i--) {
cout << numbers1[i] << endl;
}
}
and change your main to:
int main() {
int *arr1 = readNumbers();
reverseArray(arr1,6);
return 0;
}
Now, if you actually want to return this array, you would need to create a new array which holds the reverse numbers and then return that. An example of a function that does that is:
int* reverseArray(int *numbers1,int length) {
int j = 0;
int *numbers2 = new int[length];
for (int i = length-1; i >=0; i--) {
numbers2[j] = numbers1[i];
j++;
}
return numbers2;
}
There are probably better ways to do this, but this is just one solution. Regardless, you should always be careful when allocating memory yourself.
Hope my question isn't confusing. I'll explain that with code.
I'm learning constructor/desctructor and new/delete in C++. While comparing two piece of code, I'm thinking about where the object and it's members are allocated.
I got a little bit confused when I see the new in constructor and main, and delete in destructor and main:
In the first example, I think local object c is allocated in stack. And that means, members list pointer, two int values (size and capacity) are all in stack. The object also contains an array in size 10, however the array itself is allocated in heap since new is used. When the program ends, the local object c (including the pointer) will be freed automatically. And the array pointed by pointer list will be freed as well, by destructor. Is that correct?
#include <iostream>
#include <string>
using namespace std;
class Collector {
int * list;
int size;
int capacity;
public:
// Default constructor
Collector(){
// We must define the default values for the data members
list = nullptr;
size = 0;
capacity = 0;
}
// Parameterized constructor
Collector(int cap){
// The arguments are used as values
capacity = cap;
size = 0;
list = new int[capacity];
}
bool append(int v){
if (size < capacity) {
list [ size++ ] = v;
return true;
}
return false;
}
// A simple print function
void dump(){
for(int i = 0 ; i < size ; i++) {
cout << list[i] << " ";
}
cout << endl;
}
~Collector(){
cout << "Deleting the object " << endl;
if (size > 0)
delete[] list;
}
};
int main(){
Collector c(10);
for (int i = 0 ; i < 15 ; i++){
cout << c.append(i) << endl;
}
}
Now compared with the second example, object is created with new. So all members including pointer and two int values are all allocated from heap. The array itself is also in heap for the same reason as the first example. Before the program ends, there is a delete so the pointer and two int values are all freed. The array is also freed since the desctructor is called when delete command is issued. Is my understanding correct?
#include <iostream>
#include <string>
using namespace std;
class Collector {
int * list;
int size;
int capacity;
public:
// Default constructor
Collector(){
// We must define the default values for the data members
list = nullptr;
size = 0;
capacity = 0;
}
// Parameterized constructor
Collector(int cap){
// The arguments are used as values
capacity = cap;
size = 0;
list = new int[capacity];
}
bool append(int v){
if (size < capacity) {
list [ size++ ] = v;
return true;
}
return false;
}
// A simple print function
void dump(){
for(int i = 0 ; i < size ; i++) {
cout << list[i] << " ";
}
cout << endl;
}
~Collector(){
cout << "Deleting the object " << endl;
if (size > 0)
delete[] list;
}
};
int main(){
Collector *c;
c = new Collector(10);
for (int i = 0 ; i < 15 ; i++){
cout << c->append(i) << endl;
}
delete c;
cout << "Exiting program" << endl;
}
I am trying to insert int array x to int *v. here is my code . please provide me with optimal solutions and the reason behind it.
there is an error in this line. Instead of copying array value its taking garbage value. line v1=x;
class vector
{
int *v;
int size;
public:
vector(int m)
{
v = new int[size = m];
for (int i = 0; i < size; i++)
v[i] = 0;
}
vector(int *a)
{
for (int i = 0; i < size; i++)
v[i] = a[i];
}
int operator *(vector &y)
{
int sum = 0;
for (int i = 0; i < size; i++)
sum += v[i] * y.v[i];
return sum;
}
void disp()
{
for (int i = 0; i < size; i++)
cout << v[i] << " ";
cout << "\n";
}
};
int main()
{
clrscr();
int x[3] = { 1,2,3 };
int y[3] = { 4,5,6 };
vector v1(3);
//v1.disp();
vector v2(3);
v2.disp();
v1 = x;
v1.disp();
//v2=y;
v2.disp();
int r = v1 * v2;
cout << "R = " << r;
getch();
return 0;
}
You forgot to add the assignment operator in your vector class:
vector & operator=(int *a)
{
for (int i = 0; i < size; i++)
v[i] = a[i];
return *this;
}
In the the line
v1=x;
May be, you are expecting it to invoke the second constructor which takes int* as argument. But it won't happen.
It can be seen as Type Conversion from Basic type to Class type. where we expect appropriate constructor will get invoked.
see http://www.hexainclude.com/basic-to-class-type-conversion/
But remember, Constructor will be invoked only once after the creation of object.
Here, in the line
vector v1(3);
the first constructor was already invoked. Then the line
v1=x;
won't invoke the second constructor now.
For every class, = operator is default overloaded . That is the reason why we can easily assign objects to one another.
Therefore, the line v1=x invokes default overloaded assignment = operator.
Here, it treats address of array x i.e., &x[0] as address of class object. As it is not address of vector class object
=> it results a Segmentation fault.
YOUR ANSWER
To assign int array to int pointer i.e., to the member variable int* v of the vector class,
overload assignment operator = inside the class .
or
Initialize the class object to array in first line itself. i.e.,
vector v1=x; // modify the class constructor to have size as a constant.
I've deleted previous dynamic double "a" array and created a new same-named long int array. But code::blocks gives me an error: "a has a previous declaration as double a". Here is the program:
/*Write a C++ program that receives integer n and
creates a dynamic array a of n size
of doubles, then shows a
maximum number in array, then array a is
deleted, then again receives
integer n and creates a dynamic array
a of n size of long int, then shows minimum number
in array.*/
#include<iostream>
using namespace std;
int main(){
double temp;
int *n = new int;
cin >> *n;
double *a = new double[*n];
for (int i=0;i<*n;i++)
cin>>a[i];
for (int i = 0; i<*n; i++){
if (temp<a[i]){
temp=a[i];
}
}
cout << "Max. num in array: " << temp << endl;
delete[] a;
cin >> *n;
long int *a = new long int[*n];
for (int i=0;i<*n;i++)
cin>>a[i];
for (int i = 0; i<*n; i++){
if (temp>a[i]){
temp = a[i];
}
}
cout << "Min. num in array: " << temp << endl;
delete n;
delete []a;
}
You cannot re-define a variable that was previously defined in the same scope. Initially you have
double *a; // a is a pointer to double
then you try
long int *a; // a is a pointer to long int
It doesn't matter that you delete[] a;. The variable a continues to exist, it is of a pointer type. Of course its allocated memory is deleted, but still you cannot re-declare it.
The instructor probably meant
char* a;
a = new char[n*sizeof(double)];
//...
delete[] a;
a = new char[n*sizeof(long int)];
If you don't want a conflict and want to keep the pointer of type double* and long int* respectively, you can put the variable inside a scope, like
{
double *a = new double[n];
// ...
delete[] a;
} // end of scope, `a` ceases to exist
{ // new scope
long int *a = new long int[n];
// ...
delete[] a;
}
You can't redeclare it. As you have freed up the memory space. But consider this, you can again allocate memory to the double array
Check here Here
#include<iostream>
using namespace std;
int main()
{
int *a;
a = new int[3];
for (int i = 0; i < 3; i++)
{
a[i] = i * 2;
cout << a[i] << endl;
}
delete [] a;
a = new int[3];
for (int i = 0; i < 3; i++)
{
a[i] = i * 3;
cout << a[i] << endl;
}
delete [] a;
return 0;
}
variable "a" is declared as double at first in main function, and you can't use "a" for another variable's name in same scope.
I know how to create a array of dynamic objects.
For example, the class name is Stock.
Stock *stockArray[4];
for(int i = 0 ; i < 4;i++)
{
stockArray[i] = new Stock();
}
How do you change this to dynamic array of dynamic objects?
What I tried:
Stock stockArrayPointer = new Stock stock[4];
It doesn't work and the error is "The value of Stock** cannot be used to initalize an entity of type Stock.
Second question is after the creation of dynamic array of dynamic objects, what is the syntax to access the pointers in the array.
Now, I use stockArray[i] = new Stock(); How will this change?
Need some guidance on this...
If you are using c++ then you shouldn't reinvent the wheel, just use vectors:
#include <vector>
std::vector< std::vector< Stock > > StockVector;
// do this as many times as you wish
StockVector.push_back( std::vector< Stock >() );
// Now you are adding a stock to the i-th stockarray
StockVector[i].push_back( Stock() );
Edit:
I didn't understand your question, if you just want to have and array of arrays allocated on the heap just use:
Stock** StockArrayArray = new Stock*[n]; // where n is number of arrays to create
for( int i = 0; i < n; ++i )
{
StockArrayArray[i] = new Stock[25];
}
// for freeing
for( int i = 0; i < n; ++i )
{
delete[] StockArrayArray[i];
}
delete[] StockArrayArray;
The type of a variable to a dynamic array is a pointer to the first object of the array. You want an array of dynamically allocated Stock objects, so an array of pointers to Stock, so your variable is a pointer to a pointer to Stock:
int n = 4; // dynamic size of the array;
Stock** stockArray = new Stock*[n];
for (int i = 0; i != n; ++i)
{
stockArray[i] = new Stock();
}
and freeing it:
for (int i = 0; i != n; ++i)
{
delete stockArray[i];
}
delete[] stockArray;
Stock* stockArrayPointer = new Stock [4];
works only if the Stock class has a zero argument constructor
if it does not have any zero argument constructor you cannot create an array of dynamic objects dynamically
you can as said create a array of dynamic object with a static array like
Stock stockArrayPointer[4]={Stock(args),Stock (args)};
but the syntax
Stock* stockArrayPointer=new Stock[4]{Stock(args),Stock (args)}; does not hold
or as said
use vectors...
vectors are memory allocated on heap
so the vector is a dynamic allocation
vector<Stock> V;
V.push_back(Stock(args));
or
V.push_back(new Stock(args));
The reason why
Stock* stockArrayPointer=new Stock[4]{Stock(args),Stock (args)};
does not hold
is because
this means
you are using the new operator incorrectly
I did something which worked perfectly:
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class student {
string name;
int age;
int roll;
public:
student() {
name="";
age=0;
roll=0;
}
student (string n, int a, int r) {
name=n;
age=a;
roll=r;
}
void show_details ();
};
void student::show_details() {
cout << "Name: " << name << "\n";
cout << "Age: " << age << "\n";
cout << "Roll No: " << roll << "\n";
}
int main() {
string a; int b, c, n;
cin >> n;
student **obj;
obj=(student**)malloc(n*sizeof(student*));
for (int i=0; i<n; i++) {
cin >> a;
cin >> b;
cin >> c;
obj[i]=new student(a,b,c);
}
for (int i=0; i<n; i++) {
obj[i]->show_details();
}
for (int i=0; i<n; i++) free (obj[i]);
free (obj);
}
Yes... I used pointer to pointer for the array part, and it worked perfectly for variable sized arrays.