In the both code snippets there are used variable length arrays because in their declarations there are not used integer constant expressions that specify the number of elements in the arrays.
There is no dynamically allocated array.
The first code snippet has a bug in the statement with the call of scanf
.
scanf(" %d",n);
The argument shall be a pointer to the variable n
.
scanf(" %d", &n);
That is to change the variable n
by means of the function scanf
you have to pass it to the function by reference.
In C passing by reference means passing an object indirectly through a pointer to it. So dereferencing the pointer the function will have a direct access to the object that must be modified.
Pay attention to that in the second code snippet changing the value of the variable n
after the array declaration does not change the number of elements in the array a
.
int n;
n=6;
int a[n][n];
...
n=7;
...
n=4;
The array a
will have exactly 6
elements according to the value stored in the variable n
before the array declaration.
Here is a demonstrative program.
#include <stdio.h>
int main(void)
{
size_t n;
do
{
printf( "Enter number of rows/columns (greater than 0 ) = " );
} while ( !( scanf( "%zu", &n ) == 1 && n != 0 ) );
int a[n][n];
printf( "The size of the array declared like int a[%zu][%zu] is %zu.\n",
n, n, sizeof( a ) );
return 0;
}
The program output might look like
Enter number of rows/columns (greater than 0 ) = 10
The size of the array declared like int a[10][10] is 400.
A variable length array shall have automatic storage duration (that is it may not be declared for example in a file scope or have the storage specifier static
; it may be declared in a block scope).
From the C Standard (6.7.6.2 Array declarators)
4 If the size is not present, the array type is an incomplete type. If
the size is * instead of being an expression, the array type is a
variable length array type of unspecified size, which can only be used
in declarations or type names with function prototype scope; such
arrays are nonetheless complete types. If the size is an integer
constant expression and the element type has a known constant size,
the array type is not a variable length array type; otherwise, the
array type is a variable length array type. (Variable length arrays
are a conditional feature that implementations need not support; see
6.10.8.3.)