Newing a More Complicated cdecl

I have recently discovered a wonderful source of information regarding the method used to read cdecl: http://www.unixwiz.net/techtips/reading-cdecl.html

Now, I have been messing around for a while, and here is a function that:

Returns: a pointer to an array of 4 pointers to int.

Now, on the 4th line; I can not seem to get the type syntax right. I have attemtped many combinations. What eventually worked was to simply reinterpret_cast, however, this should not always give me defined behaviour on all platforms.

So, what's the correct way to do it?

1
2
3
4
5
6
7
8
int (*(*comp(const int x))[4])
{
    int *(*arr)[4];
    arr = reinterpret_cast<decltype(arr)>(new (int *[4])); // Here
    for (int i = 0; i < 4; ++i)
        *(arr[i]) = new int(x + i);
    return arr;
}
Here's what I've tried out. Is it simply impossible? Apparently the type of "arr" is int* (*)[4]; it seems that new simplifies it to int ** (which is correct as well), and the compiler refuses to assign this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int (*(*comp(const int x))[4])
{
    int *(*arr)[4];
    arr = reinterpret_cast<decltype(arr)>(new (int *[4])); // Works perfectly; but syntactically dirty.
//    arr = new (int *[4]); // error: cannot convert 'int**' to 'int* (*)[4]' in assignment
//    arr = new (int (*)[4]); //error: cannot convert 'int (**)[4]' to 'int* (*)[4]' in assignment
//    arr = new (int *(*)[4]); // error: cannot convert 'int* (**)[4]' to 'int* (*)[4]' in assignment
//    arr = new (int *()[4]); // error: 'type name' declared as function returning an array
//    arr = new int *(*)[4]; // error: expected ';' before '[' token
//    arr = new (int *)[4]; // error: array bound forbidden after parenthesized type-id
//    arr = new (int) *[4]; // error: expected identifier before numeric constant
//    arr = *new decltype(arr); // Compiles: Works partially, garbage data in the first element.
//    arr = new decltype(*arr); // error: new cannot be applied to a reference type
    arr = new (int (*[4]));
    for (int i = 0; i < 4; ++i)
        *(arr[i]) = new int(i);
    return arr;
}
}
Topic archived. No new replies allowed.