简体   繁体   中英

print an array after deep copying in c++ classes

I want to achieve the following behaviour:

  1. The class DataSequence has a pointer that points to an array in the main function.
  2. print the array when an object in initialised of the class DataSequence
  3. create a deep-copy of the same object (via a copy constructor) and print it when the object is formed.

The code I have written is as follows:

#include<bits/stdc++.h>
using namespace std;

class DataSequence{
float *ptr;
int _size;

public:
    DataSequence(float input[] , int size){
        _size = size;
        ptr = new float; ptr = input;
        //print the array
        cout << "Main constructor" << endl;
        for(int i=0 ; i<_size; ++i){
            cout << *(ptr+i) << " ";
            // ++ptr;
        }
    }

    //copy constructor
    DataSequence(DataSequence &d){
        _size = d._size;
        ptr = new float; *ptr = *(d.ptr);
        //print the array
        cout << "copy constrructor" << endl;
        for(int i=0 ; i<_size ; ++i){
            cout << *(ptr+i) <<" ";
            // ++ptr;
        }
    }
 };


int32_t main(){
int size=4;
float input[size];
int bins;
input[0] = 3.4;
input[1] = 1.3;
input[2] = 2.51;
input[3] = 3.24;   

DataSequence d(input , size);
cout << endl;
DataSequence d1 = d;

return 0;
}

The output is as follows

Main constructor
3.4 1.3 2.51 3.24
copy constrructor
3.4 2.42451e-038 -2.61739e-019 3.20687e-041

I am unable to figure out why I am getting garbage from the copy constructor, can someone help.

This statement:

ptr = new float;

only allocates a single float . That means in this loop:

for(int i=0 ; i<_size; ++i){
    cout << *(ptr+i)

as soon as i is greater than 0, you dereference invalid memory, which is undefined behavior. This results in a program that can do anything, including producing the "garbage" output you see.

If you want to allocate an array, you need to do:

ptr = new float[_size];

and to delete it, you need to do:

delete [] ptr;

Note that even if you allocate memory correctly as shown above, you are not actually copying the data from the argument. Just setting pointers would do a shallow copy which is not what you want.

You can do a deep copy like this:

std::copy(d.ptr, d.ptr + _size, ptr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM