Pointer to array and errors C2057, C2540

340 views Asked by At

I want to do something like:

const int N = 10;
void foo (const int count)
{
  int (* pA) [N][count] = reinterpret_cast<int(*)[N][count]>(new int[N * count]);
  ...
}

But my compiler (VS2010) doesn't want to do it:

error C2057: expected constant expression
error C2540: non-constant expression as array bound

Such a way he expresses his dissatisfaction with the count.

I know, how it can be worked around by implementing a slightly different way. But I just don't get, why does C++ forbid me to use this way. I understand, why C++ needs to know on-stack arrays size at compile time (to allocate array memory). But why the same restrictions are necessary with respect to pointers to array (after all, pointer is just a tool to work with that allocated memory)?

1

There are 1 answers

0
Ben Voigt On BEST ANSWER

Well, actually what you want is in principle alright, but you're using the wrong syntax.

All dimensions except the first have to be compile-time constants, because they're used in pointer arithmetic. The first one can be runtime varying. This works:

int (* pA)[N] = new int[count][N];

Remember that an array is compatible with pointer-to-element-type, and subscripting works exactly the same on both. So when you have a 2-D array allocated (array of arrays), you should store a pointer-to-1D-array.

There's no way to do int[N][count], though, because that would need an array of elements (subarrays) of variable size.

Furthermore, note that N is a constant-expression, but count is not. Even though they both have the same type, count is a parameter, determined at runtime.

If you want to accept a constant integral expression as an argument, make it a template argument:

template <int count>
void foo()

Now count is a constant expression just like N.