C arrays are somewhat difficult to understand syntactically in C++ and can take some getting used to. Although a 1D array decays to a pointer:
void fn1(int x[2]) {}
void fn2(int*x) {}
fn1() and fn2() have the same function signature.
An array actually does have a type that includes how many elements are in the array. As in:
void fn(int (&)[2]) {}
fn() will only accept a 2 element int array.
Thing is, I can only see that the array of a fixed number of elements can only be generated by stack, file scope or struct/class allocation with that signature:
int twoElementArray[2];
If I were to dynamically allocate it on the heap, I can't seem to get the same signature. I thought that I might be able to cast it, but without success:
int (&array)[2] = reinterpret_cast<int(&)[2]>(new int[2]); // FAIL!
Any ideas as to how this might be accomplished if at all?
EDIT: Although I selected an answer, it actually doesn't actually cast anything, but uses a definitely better method then casting (better not to cast if not required IMO). However, it technically doesn't answer the question since the question asked if there's "a way of casting a pointer to an array type?" The answer is yes.
int (&array)[2] = *reinterpret_cast<int(*)[2]>(new int[2]); // SUCCESS!
Note that I don't necessarily recommend doing this, but it does answer the question. If I needed to convert a pointer to an array type though, that would be how to do it. Read the picked answer for a better solution when using operator new[].
fn1()was part of my explanation as to how arrays work in C++ for the uninitiated. Yes, I could do:void fn3(int* array, size_t FIXED_SIZE) {}or alternativelyvoid fn3(int[] array, size_t FIXED_SIZE) {}which is a common workaround. However, I was trying to utilise the type system to stop the decoupling of the array from it's size.