Do you want to use:
#include <stdlib.h> /* ... */ int *arr; scanf("%d", &n); arr = malloc(sizeof(int) * n);
Thus, arr gets a dynamic allocation at runtime, so it can be of any size depending on input n .
What you originally did (that is, declaring arr[n] after receiving n via scanf: scanf("%d", &n); int arr[n]; ) is not a good idea, because it uses variable-length Arrays , function C, which is optional in the latest standard C.
You see that arr is created at compile time, and you can usually initialize it only with a constant expression known at compile time, which n , the variable obtained as user input, is not explicitly. Arrays of variable length are a sign of a language that basically allows you to bypass this rule, that is, they allow you to initialize an array with a length not known at compile time. It was standardized in C99 , but was listed as "optional" as C11 .
What you did after that ( int arr[n]; scanf("%d", &n); ) is pretty illogical, because you declare arr as an array of integers n before you get the value n as user input, and, know its value. It prints garbage because n initially initialized with an undefined garbage value, and this is what your VLA size becomes when you declare it:
int arr[n];
source share