+ 3

Why the output is not correct\n?

#include <stdio.h> #include <stdlib.h> // program to find largest and smallest from array int main() { int in;//no of input elements printf("Enter total number of elements");//no of elements scanf("%d",&in); int a[in]; printf("Enter integer to find largest and smallest\n"); int l = a[0],i,s=a[0]; for(i=0;i<in;i++) { scanf("%d",&a[i]); } for(i=1;i<in;i++)//test loop { if(a[i]>l) { l=a[i]; } if(a[i]<=s) { s=a[i]; } } printf("Max is %d and min is %d",l,s); return 0; }

24th Jun 2020, 6:01 AM
Coding San
Coding San - avatar
10 ответов
+ 3
Firstly you can't make array with variable It has to be const If you want to make array with variable then try to make dynamic Array like this int a=(int*) malloc(in*sizeof(int)) ;
24th Jun 2020, 6:10 AM
ycsvenom
ycsvenom - avatar
+ 3
And you have to declare l, s after collecting the data of a
24th Jun 2020, 6:13 AM
ycsvenom
ycsvenom - avatar
+ 1
The size of an array must be known at compile time. If you want to work with unknown-sized data, then you should probably use dynamic memory allocation. The reason is that an array is stack-allocated, and therefore must have a known and fixed size.
24th Jun 2020, 6:13 AM
Théophile
Théophile - avatar
+ 1
YCS-Venom It is in C language, so 'malloc' (or 'calloc', it is better in that case) must be used 😉
24th Jun 2020, 6:15 AM
Théophile
Théophile - avatar
+ 1
Sorry Théophile i realized it now 😅 And I have change it
24th Jun 2020, 6:23 AM
ycsvenom
ycsvenom - avatar
+ 1
Robin thats right, I was false. I spoke too quickly, I'm sorry... I really did believe that it wasn't possible, but I was wrong. I have just one question : if the requested size exceeds the stack size limit... Is it then allocated on the heap?
24th Jun 2020, 7:59 AM
Théophile
Théophile - avatar
+ 1
You assign value of a[0] in l and s before assign whole array So l and s have a garbage value . assigning the value to l and s after assigning array surely it will work 👍 Which creates problems to your code And you can also do this code by shorting
24th Jun 2020, 6:49 PM
Pragnenkumar Amadavadi
0
Robin VLA can't be permitted here since the value is unknown at compile time : it depends on the user input. EDIT : I said nothing, Robin, I'm sorry. But I believed it was impossible. My bad
24th Jun 2020, 7:42 AM
Théophile
Théophile - avatar
0
Hi younus Bangladesh
25th Jun 2020, 1:21 PM
MD Yonus
MD Yonus - avatar
0
Hii
26th Jun 2020, 2:48 AM
Sandeep Ku. Tudu
Sandeep Ku. Tudu - avatar