4

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.

1
  • 1
    The variable b is an array of 3 pointers. Why do you want a cast a void pointer into it? Commented Oct 12, 2010 at 17:22

2 Answers 2

10

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 for casts to void* which are implicit and from void* to any other pointer, which can be done using a static_cast.)

Sign up to request clarification or add additional context in comments.

Comments

9

Perhaps you mean to do

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

?

A static_cast version is also possible.

1 Comment

@Carlos: If you find this answer was what you needed, please vote it up and accept it (the check under the votes). Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.