views:

118

answers:

2

Hello

I'm having problems getting this to 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 can't use generic types for what i need.

Thanks in advance.

+7  A: 

Arrays are second-class citizen in C (and thus in C++). For example, you can't assign them. And it's hard to pass them to a function without them degrading to a pointer to their first element.
A pointer to an array's first element can for most purposes be used like the array - except you cannot use it to get the array's size.

When you write

void * pointer = a;

a is implicitly converted to a pointer to its first element, and that is then casted to void*.

From that, you cannot have the array back, but you can get the pointer to the first element:

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

(Note: casting between pointers to unrelated types requires a reinterpret_cast, except casts from void* to any other pointer, which can be done using a static_cast.)

sbi
+1  A: 

Perhaps you mean to do

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

?

A static_cast version is also possible.

Ben Voigt
Ben, this worked perfectly.
Carlos Familia
Tanks very much!
Carlos Familia
@Carlos: If you find this answer was what you needed, please vote it up and accept it (the check under the votes). Thank you.
Armen Tsirunyan