Search code examples
arrayscscanfdeclarationvariable-length-array

Why does array with variable-sized work but not dynamic array?


First of all, I am new to programming and don't know what "variable-sized array" and "dynamic array" mean. I am just using those words to describe my situation. Feel free to edit with correct nomenclature. Now to the question, I have following pieces of code:-

...
int n;
printf("Enter number of rows/columns = ");
scanf(" %d",n);
int a[n][n];
...

and

...
int n;
n=6;
int a[n][n];
...
n=7;
...
n=4;
...

Both of them are compiled successfully.

  • In first case, upon execution program crashes after scanf() function.
  • Second case works perfectly.

Why?


Solution

  • Use of & in scanf()

    When you scan for user input using scanf from <stdio.h>, you need to pass a pointer to it. You can read more about why that's the case here: Use of & in scanf() but not in printf()

    int n;
    printf("Integer: ");
    scanf("%d", &n);
    int a[n][n];
    

    Variable-length array

    A variable-length array is just an array whose length is determined at run time instead of at compile time. In your case the length is determined by the variable n which makes it a variable-length array. And as Eugene Sh. mentioned in the comments, changing the variable n doesn't modify the array's length after defining it.