Your code, changed a little:
Code:
#include <stdio.h>
#include <stdlib.h> // EXIT_SUCCESS and EXIT_FAILURE are defined here.
int main ( void )
{
size_t i, size;
int largest;
fputs ( "Enter number of elements of the array: ", stdout );
fflush ( stdout ); // just to be sure stdout is flushed before scanf.
if ( scanf ( "%zu", &size ) != 1 )
{
fputs ( "ERROR!\n", stderr );
return EXIT_FAILURE;
}
// FIX: Here it is advisable to limit the 'size' because the
// variable length array will be allocated on stack.
if ( size > 4096 ) // 16 KiB stack limit.
{
fputs( "ERROR! Too many elements.\n", stderr );
return EXIT_FAILURE;
}
// If you plan to use VLA, this 'array' must be defined AFTER
// you have size defined. Is not, you should 'malloc' the buffer, as in:
//
// int *array;
//
// if ( ! ( array = malloc( sizeof( int ) * size ) ) )
// {
// fputs( "ERROR! Memory allocation.\n" );
// return EXIT_FAILURE;
// }
//
// In that case, remember to call free( array ) somewhere after the buffer isn't
// necessary anymore.
//
// Using VLA here:
int array[size];
printf ( "Enter %zu elements of the array (separated by space): ", size );
fflush ( stdout );
for ( i = 0; i < size; i++ )
if ( scanf ( "%d", &array[i] ) != 1 )
{
fputs ( "ERROR!\n", stderr );
return EXIT_FAILURE;
}
// Find the largest element.
largest = array[0];
for ( i = 1; i < size; i++ )
if ( array[i] > largest )
largest = array[i];
printf ( "Largest = %d\n", largest );
return EXIT_SUCCESS;
}