Menmikimen Menmikimen - 1 month ago 11
C++ Question

copying an array of int*

I have to create a copy constructor for my object, which look like this;

class DTable {
private:
std::string s_name;
int* *array;
int size;

public:
DTable();
DTable(std::string sName);
DTable(DTable &pcOther);
~DTable();

void vSetName(std::string sName);
std::string info();
int getValue(int index, bool &ok);
bool setValue(int index, int val);

const int defaultArrSize = 10;
const std::string defaultArrName = "Default Name";
};


Where array variable points at array of int*. Copy constructor i came up with looks like this;

DTable::DTable(DTable & pcOther) {
s_name = pcOther.s_name + "_copy";
size = pcOther.size;
array = new int*[size];
for (int i = 0; i < size; i++) {
array[i] = new int;
*array[i] = pcOther.*array[i];
}
}


The problem is that, i just cannot copy values of pointed int array to another array. Solution like this leaves me with error


expression must have pointer to member type


Also,

array[i] = pcOther.array[i];


is wrong, because that just copies references, so after altering one object, copy of it will be altered too. I want to avoid that.

I'd love to use different structure for this, but it has to be dynamically allocated array of int*

dd2 dd2
Answer

You can use the memcpy(),

void * memcpy ( void * destination, const void * source, size_t num );

or

*array[i] = *(pcOther.array[i])

for e.g.

DTable::DTable(DTable & pcOther) {
    s_name = pcOther.s_name + "_copy";
    size = pcOther.size;
    array = new int*[size];
    for (int i = 0; i < size; i++) {
        array[i] = new int;
        *array[i] = *(pcOther.array[i]);
        // or
        memcpy ( array[i], pcOther.array[i] , sizeof(int)*1 );
    }
}