Question

is it possible to copy

MyStruct * const * array1

to

MyStruct * array1

but just as a shallow copy? I need sort it and write back into it and I want changes in array 1 too

EDIT: Im stupid, I overlooked ** at array1 then it makes sense.

No correct solution

OTHER TIPS

I guess you mean const MyStruct * array1?

In any case you can use const_cast to change constness of a pointer:

const MyStruct * array1;
MyStruct * array2 = const_cast<MyStruct *>(array1);

Or

const MyStruct * const array1;
MyStruct * array2 = const_cast<MyStruct *>(array1);

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top