Scottycm
Scottycm

Reputation: 3

Trouble with array in function

I'm having trouble with a program that takes a 2d array, calculates the average of each row, then stores these averages in a new array. Where I seem to be having the problem is with actually assigning the averages to the new 1d array. If I put a print statement in the loop directly after the value has been assigned it seems to be there and work fine. But once I try to display whats in the array with my created display function it is all zeroes except for one entry that's a random large number.

Sample Output:

36.25 58.00 52.00 42.00 51.75 47.00 <--- From print within average function (Correct)

0.000 0.000 0.000 0.000 406778500087808.000 0.000 <--- From created display function

void row_average(int vals2d[][4], int rows, int cols)
{
    int k, l, sum;
    float avg, rowavg[6];
    for (k=0; k<rows; k++){
        sum = 0;
        avg = 0;
        for (l=0; l<cols; l++){
            sum = sum + vals2d[k][l];
            avg = (float)sum/4;
        }
        rowavg[k] = avg;
        printf("%.2f  ", rowavg[k]);
    }
}

void array_1display(float rowavg[], int size)
{
    int m;
    for (m=0; m<size; m++){
        printf("%.3f  ", rowavg[m]);
    }
}

int main()
{
    float rowavg[6];
    int vals2d[6][4] ={
    {12,54,34,45},
    {68,76,65,23},
    {75,23,76,34},
    {6,45,58,59},
    {35,67,93,12},
    {66,90,25,7}
    };

    row_average(vals2d, 6, 4);
    printf("\n");
    array_1display(rowavg, 6);
}

Upvotes: 0

Views: 49

Answers (1)

Ibrohim Kholilul Islam
Ibrohim Kholilul Islam

Reputation: 756

You need to pass your array rowavg[] or make it global.

Here is some correction:

#include <stdio.h>

void row_average(int vals2d[][4], int rows, int cols, float rowavg[])
{
    int k, l, sum;
    float avg;
    for (k=0; k<rows; k++){
        sum = 0;
        avg = 0;
        for (l=0; l<cols; l++){
            sum = sum + vals2d[k][l];
            avg = (float)sum/4;
        }
        rowavg[k] = avg;
        printf("%.2f  ", rowavg[k]);
    }
}

void array_1display(float rowavg[], int size)
{
    int m;
    for (m=0; m<size; m++){
        printf("%.3f  ", rowavg[m]);
    }
}

int main()
{
    float rowavg[6];

    int vals2d[6][4] ={
            {12,54,34,45},
            {68,76,65,23},
            {75,23,76,34},
            {6,45,58,59},
            {35,67,93,12},
            {66,90,25,7}
        };

    row_average(vals2d, 6, 4, rowavg);
    printf("\n");
    array_1display(rowavg, 6);
}

Upvotes: 1

Related Questions