Array Pointer and Errors C2057, C2540

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 this:

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

Thus, he expresses his displeasure count

.

I know how to get around this by implementing it a little differently. But I just don't understand why C ++ does prevent me from using this way. I understand why C ++ needs to know the size of the array on the stack at compile time (to allocate the memory of the array). But why are the same restrictions necessary for pointers to an array (after all, a pointer is just a tool to work with that allocated memory)?

+3


source to share


1 answer


Well, actually what you want is basically ok, but you're using the wrong syntax.

All dimensions other than the first must be compile-time constants, as they are used in pointer arithmetic. The first one can vary depending on the execution time. It works:

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

      

Remember that array is pointer-element-type compatible, and subscript works the same on both. So when you have a 2-dimensional array allocated (array of arrays) you must store a 1D pointer array.

There is no way to do it int[N][count]

, although it would require a variable sized array of elements (subarrays).



Also, note that this N

is a constant expression, but count

it is not. Although both are of the same type, count

this is a parameter defined at runtime.

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

template <int count>
void foo()

      

count

Is now a constant expression just like N

.

+2


source







All Articles