Consider the C code below:
#include<stdio.h>
int main()
{int n,i;
scanf("%d",&n);
int a[n]; //Why doesn't compiler give an error here?
}
How can I declare an array when the compiler doesn't know initially?
When the the exact size of array is unknown until compile time, you need to use dynamic memory allocation. In the C standard library, there are functions for dynamic memory allocation: malloc, realloc, calloc and free.
These functions can be found in the <stdlib.h> header file.
If you want to create an array you do:
int array[10];
In dynamic memory allocation you do:
int *array = malloc(10 * sizeof(int));
In your case is:
int *array = malloc(n * sizeof(int));
If you allocate a memory position, never forget to deallocate:
if(array != NULL)
free(array);
Memory allocation is a complex subject, I suggest you search for the subject because my answer was simple. You can start with this link:
https://www.programiz.com/c-programming/c-dynamic-memory-allocation
nread by the precedingscanf()).