Home > OS >  C Program returns garbage value for avg
C Program returns garbage value for avg

Time:05-22

When running this program using pointers and arrays to calculate the grade point average from the user input, it outputs a garbage value. How can I alter the code so that the output is correct?

void Insert_Grades(int *array) 
{ 
    int grades[4];
    int i;
    
    for (int i = 0; i < 4; i  ) 
    {
        printf("Enter grade %d: ", i   1);
        scanf("%d", &grades[i]); 
    } 
    array = grades;
}

void Calculate_Avg(int *array)
{
    int i;
    float avg;
    float sum = 0;

    for (i = 0; i < 4; i  ) 
    {
        sum  = *(array   i);
    }
    avg = sum / 4;
    printf( "Grade point average is: %f ", avg);
}

int main() 
{
    int grades[4];
    int i;

    printf("Enter the number of grades:\n");
    Insert_Grades(grades);

    Calculate_Avg(grades); 
    printf("\n"); 
  
    return 0;
}

CodePudding user response:

you cant assign arrays.

This operation assigns local pointer array with reference of the local array grades. For the extral world this operation means nothing.

array = grades;

You need to copy values instead.

memcpy(array, grades, sizeof(grades));

or

for (size_t index = 0; index < 4; index  )
   array[index] = grades[index];

CodePudding user response:

There are multiple problem in your code:

  • in function Insert_Grades, value are read into the local array grades. The last instruction array = grades has no effect because it only modifies the argument value, which is just local variable, a pointer to int that now points to the first element of grade array.

    This explains why the program outputs garbage because the array grades defined in the main() function is uninitialized and is not modified by Insert_Grades().

    You could copy the array grade to the caller array pointed to by array, but it seems much simpler to use the array pointer to read the values directly where they belong.

  • the variable i is defined multiple times, with nested scopes.

  • you should test the return value of scanf() to detect invalid or missing input.

Here is a modified version:

#include <stdio.h>

void Insert_Grades(int *array, int count) { 
    for (int i = 0; i < count; i  ) {
        printf("Enter grade %d: ", i   1);
        if (scanf("%d", &array[i]) != 1) {
            fprintf(stderr, "invalid input\n");
            exit(1);
        }
    } 
}

float Calculate_Avg(const int *array, int count) {
    float sum = 0;
    for (int i = 0; i < count; i  ) {
        sum  = array[i];
    }
    return sum / count;
}

int main() {
    int grades[4];
    int count = sizeof(grades) / sizeof(*grades);
    float avg;

    printf("Enter the grades:\n");
    Insert_Grades(grades, count);

    avg = Calculate_Avg(grades, count); 
    printf("Grade point average is: %.3f\n", avg);
  
    return 0;
}
  • Related