Casting from void * to an array of objects in C ++

I have problems with work,

class A {
public:
    A(int n) {
        a = n;
    }
    int getA() {
        return a;
    }
private:
    int a;
};

int main(){

    A* a[3];
    A* b[3];

    for (int i = 0; i < 3; ++i) {
        a[i] = new A(i + 1);
    }

    void * pointer = a;

    b = (A* [])pointer;  // DOESNT WORK Apparently ISO C++ forbids casting to an array type ‘A* []’.
    b = static_cast<A*[]>(pointer); // DOESN'T WORK invalid static_cast from type ‘void*’ to type ‘A* []’

    return 0;
}

And I cannot use generic types for what I need.

Thanks in advance.

+3
source share
2 answers

Arrays are second-class citizens in C (and therefore in C ++). For example, you cannot assign them. And it is difficult to transfer their functions without humiliating them to a pointer to their first element.
A pointer to the first element of an array can be used for most purposes, like an array, except that you cannot use it to get the size of the array.

When you write

void * pointer = a;

a , void*.

, :

A* b = static_cast<A*>(pointer);

(: reinterpret_cast, void*, , void* , static_cast.)

+10

,

memcpy(b, (A**)pointer, sizeof b);

?

A static_cast.

+6

Source: https://habr.com/ru/post/1769198/


All Articles