C programming : functions with arrays

前端 未结 1 548
一个人的身影
一个人的身影 2021-01-29 13:40

I\'m trying to write a function which finds the largest value in a 2d array with row of 4 and col of 4 where the 2d array is filled with user input. I know my main error is with

相关标签:
1条回答
  • 2021-01-29 13:54

    There are a few problems to address here, the first is you can't have int array[][] as a parameter, you need to provide all but the first dimension, int array[][4] would suffice in this limited case.

    However, since row and col are local variables in main they aren't visible to your largest functions body, so they'll need to be passed, make the signature

    void largest(int row, int col, int array[row][col]);
    

    Since this is a void function, it can't return any value. It will modify the array it's given in place though, so the changes will be visible.

    If you're looking for the straight-up log error, the function to find the largest is pretty crazy. A saner implementation would be to just track the largest element you've seen so far:

    int largest(int row, in col, int array[row][col]) {
        int big = array[0][0]; // assume the first element is the largest
        for (int i = 0; i < row, ++i) {
            for (int j = 0; j < col; ++j) {
                if (array[i][j] > big) big = array[i][j];
            }
        }
        return big;
    }
    

    you could then call the function from main as

    int bigNum = largest(row, column, array);
    
    0 讨论(0)
提交回复
热议问题