#include <stdio.h>
//print els of an array
int main(){
int n,arr[n],i;
printf("\nenter no. of elements in the array : ");
scanf("%d",&n);
printf("\nenter elements of the array : ");
for(i=0; i < n; i++){
scanf("%d",&arr[i]);
}
for(i=0; i < n; i++){
printf("\n%d ",arr[i]);
}
return 0 ;
}
Asked
Active
Viewed 78 times
0

Yun
- 3,056
- 6
- 9
- 28

Mikael Ahlström
- 1
- 1
-
1Move the `scanf` to be above `arr[n]`. That is, need to have a value for `n` before declaring the array. – kaylum Sep 18 '21 at 04:55
-
1`n` is uninitialized before the `scanf()`, do `int arr[n]` *after* `scanf("%d",&n);`. – JASLP doesn't support the IES Sep 18 '21 at 04:55
-
thnx kaylum & lonely programmer :) – Mikael Ahlström Sep 18 '21 at 05:06
-
Please create an answer. – Yunnosch Sep 18 '21 at 05:29
-
Don't use VLA for something like this! If you do it anyway, check the value of `n` **before** creating the VLA to ensure that it isn't "too big" – Support Ukraine Sep 18 '21 at 06:07
-
Also note that compiler support for VLAs is optional from C11 on (though most compilers do support VLA, it is no longer guaranteed) – David C. Rankin Sep 18 '21 at 07:36
1 Answers
1
To create a VLA you need to know the length provided by the user first before creating the array, so Just as JustASimpleLonelyProgrammer stated, you should only create the array after reading the value of n.
scanf("%d", &n);
int arr[n];
However, dynamic memory allocation is the more usual solution to this problem.
int* arr = (int*) malloc(n * sizeof(int));
Please refer to this answer for difference between dynamic memory allocation and VLA..

Mohamed abdelmagid
- 359
- 5
- 19