0

Initializing all the elements of a double dimensional array with constant size like this works:

int A[10][10]={0}; 

But initializing all elements of a double dimensional array with variable size specified, as below, does not works :

int n=10, m=10;
int A[m][n] = {0};

Why is it so and what is the best way to figure it out?

  • 1
    Arrays with variable size are not legal C++. So this question literally has no answer. You've been fooled by your compiler which is accepting code that is not legal. The C++ alternative to variable length arrays is `std::vector`. Use that instead and it becomes very easy. – john Apr 05 '20 at 15:11
  • 1
    Note: Variable Length Arrays are *not* a standard C++ feature. They are an *extension* supported by *some* compilers. Don't use them. Use `std::vector` instead. For GCC and Clang you can enable a warning for them `-Wvla`. I suggest doing so and also make warnings into errors `-Werror` so you don't accidentally use them (or other things the compiler can warn you about). In general, turn your warning level up as much as possible `-Wall -Wextra` is a good *start*, but far from the end of that road. – Jesper Juhl Apr 05 '20 at 15:11
  • Also use `-std=c++17` rather than the default gnu language variant that allows extensions. – Jesper Juhl Apr 05 '20 at 15:17
  • @Jesper whats the way though if I don't want to use vectors and stick to C style programming? – Ashish Chourasia Apr 05 '20 at 15:20
  • @AshishChourasia a C style array in C++ *must* have a constant size, where the size is known at *compile time*. There's no such thing as dynamic C-style arrays. You *could* heap allocate your array, but then why not just use `std::vector`? – Jesper Juhl Apr 05 '20 at 15:24
  • If you intend to use variables to create your 2D array, you have two options: 1. Make your variables constant. `const int N = 10; const int M = 10; int A[N][M] = {0};`, or 2. Make your array on the heap. `int N = 10; int M = 10; int** A = new int*[N]; for(int i = 0; i < M; i++) { A[i] = new int[M]; }` – Shaavin Apr 05 '20 at 23:05

0 Answers0