I study declaring two-dimensional dynamic arrays in C. I assumed that dynamic arrays here can be declared only with the help of references and malloc ().

At first I used malloc () in a loop.

int m, n, c; scanf("%d %d", &m, &n); int** a = (int**)malloc(m*sizeof(int*)); for (c = 0; c < m; c++) { a[c] = (int*)malloc(n*sizeof(int)); } 

Then came the only call to malloc ().

 int m, n, c; scanf("%d %d", &m, &n); int** a = (int**)malloc(m*sizeof(int*) + m*n*sizeof(int)); int* row = &a[n]; for (c = 0; c < m; row += n, c++) { a[c] = row; } 

And then I tried the elementary:

 int m, n; scanf("%d %d", &m, &n); int a[m][n]; 

And it worked. This is normal? Can this be used?

  • In the last example, your two-dimensional array will be static rather than dynamic. This will work fine, but memory will be allocated on the stack. - Alexcei Shmakov

1 answer 1

If dynamic means an array, the size of which may change during compilation, then malloc is indispensable.

If you need an array whose size is determined at run-time, then you can write int a[m][n] . Memory is allocated locally on the stack, but the size of the array cannot be changed.

This is a normal practice, but you need to keep in mind that in С++ there is no such possibility.

  • In C ++, you can use other features for this :) I truly understand that the main trouble with variable-length arrays in C is that they are placed on the stack? Simply, VC ++ 2015 does not want to support this opportunity, so the knowledge is purely theoretical ... - Harry
  • @Harry, an array declared as int a[m][n] is an array of fixed dimension. If we declare an array globally, then it will be stored in the field of global variables; if in a function, it will be stored on the stack. - insolor
  • @insolor Fixed already at runtime, right? When will the n and m values ​​be entered? - Harry
  • @Harry, as I recall, n and m should be known at the time of compilation (not in wound time). - insolor
  • @insolor Here we are talking about innovation in C - arrays with variable size, when m and n do not have to be compile time constants. So I wonder how this is solved in practice ... - Harry