-2

I'm a beginner in C, and I'm trying to create a program that calculate an array's maximum, using input from keyboard. I don't understand why this code prints 4203785. I think the algorithm is right. Can someone help me?

  int calcola_massimo(int vettore[], int size) {

        int max = vettore[0];
        int i;

        for(i = 0; i < size; i++ ){

            if(vettore[i] > max){
                max = vettore[i];
            }
        }

        return max;
    }


    int main(int argc, char *argv[]) {

        int array[10];
        int j;
        int max;

        for(j = 0; j< SIZE; j++){
            printf("Inserire valore n. %d \n", j+1);
            scanf("%d", array);
        }

        max = calcola_massimo(array, SIZE);
        printf("Il valore massimo e' : %d", max);

        return 0;
    }
Steffen D. Sommer
  • 2,896
  • 2
  • 24
  • 47

1 Answers1

2

For starters it would be better to declare the array like

int array[SIZE];

As for the loop then you have to write either

scanf("%d", array + j );

or

scanf("%d", &array[j] );

Otherwise you always enter array[0]. All other elements of the array are not initialized.

It would be better to define the function itself the following way

int * calcola_massimo( const int vettore[], size_t size ) 
{
    const int *max = vettore;
    size_t i;

    for ( i = 1; i < size; i++  )
    {
        if ( *max < vettore[i] ) max = vettore + i;
    }

    return ( int * )max;
}

because nothing prevents the user to pass size equal to 0. Your original function in this case will have undefined behaviour.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335