jeudi 9 novembre 2023

Two Dimensional Array init in C++11

I'm trying to get full understandig of C++ arrays init.

Here is the code snippet:

int main() {
    const int n= 20;
    int m;
    m = n+10;
    int (*a)[m] = new int [n][m]; //1
    int *w = new int [m]; //2
    int (*b)[n] = new int [m][n]; //3
    int (*d)[n] = new int [n][n]; //4
}

If i'll try to comple this code, i'll get the errors:

error: array size in new-expression must be constant
error: the value of 'm' is not usable in a constant expression
note: 'int m' is not const

I have read, that for array init variable must to be a const, but, if so, then i have some questions:

  1. Why is it possible to init single-dimensional array (2) using non-const variable m?
  2. Why is it possible to init two-dimensional array (3) using non-const variable m at rows number position?
  3. Why isn't possible to init two-dimensional array (1) using non-const variable m at column number position?

Just in case, I'll clarify, that i'm not looking for workarounds, another ways, etc. Just for theoretical knowledge.

Thank you!

Aucun commentaire:

Enregistrer un commentaire