Works for exactly the structure from the question... But, the second array1
replaced with another pointer parray
.
Maybe, you qualify this as a deep copy even if it is a shallow copy of the struct?
Then, maybe, the other answer is better.
struct MyStruct {
int i;
int* p;
};
int j=2;
MyStruct st={ 1, &j };
int main() {
MyStruct* parray1(&st);
MyStruct* const* array1(&parray1);
MyStruct * parray=new MyStruct();
parray->i = (*array1)->i;
parray->p = (*array1)->p;
/*
This is essentially the same as
(*parray) = *(*array1);
*/
delete parray;
}
Edit: A second example as discussed in the comments to this answer.
Here we have a non-const pointer to which we successively assign the pointer values from the const pointer-pointer array1
.
#include <iostream>
struct MyStruct {
int i;
int* p;
};
int j=2;
MyStruct st1={ 1, &j }, st2={ 2, &j };
int main() {
MyStruct* parray1[2] = {&st1, &st2};
MyStruct* const *array1(parray1);
std::cout << array1[0]->i << ' ' << array1[1]->i << '\n';
MyStruct* parray=array1[0];
parray->i = 3;
parray=array1[1];
parray->i = 4;
std::cout << array1[0]->i << ' ' << array1[1]->i << '\n';
return 0;
}
The corresponding output:
1 2
3 4
After the last comments (I think) we have reached a common interpretation of the question.
The pointers in the const array are to be copied into a non-const array where they can be re-arranged and the objects can be modified.
#include <iostream>
#include <algorithm>
struct MyStruct {
int i;
int* p;
};
int j=2;
MyStruct st1={ 1, &j }, st2={ 2, &j };
int main() {
MyStruct* parray1[2] = {&st1, &st2};
MyStruct* const *array1(parray1);
std::cout << array1[0]->i << ' ' << array1[1]->i << '\n';
MyStruct* parray[2];
std::copy(array1,array1+sizeof(parray)/sizeof(parray[0]),parray);
// some manipulation:
std::swap(parray[0],parray[1]);
parray[0]->i = 3;
parray[1]->i = 4;
std::cout << array1[0]->i << ' ' << array1[1]->i << '\n';
return 0;
}
The new output is:
1 2
4 3