Smurfer
Smurfer

Reputation: 33

Why is the program giving a wrong answer, when I am trying to find maximum of an array using call by reference?

I want to write a function, who gives me the maximum of an array and it should be with call by reference. Here is my Code:

void max_array (int *array[], int len, int *max){
    for (int i = 0; i < len; ++i) {
        if (*max < &array[i]){
            *max = array[i];
        }
    }
}

int main() {
    void print_array (int array [], int len);
        int array[] = {5,3,2,6,4,6,1};
        int len = 8;
        int max = 0;
        max_array(array, len, &max);
        printf("Max of Array: %d \n", max);

        return 0;
}

Like u see there is something wrong. My Output is like 158879987 so an address.

Upvotes: 0

Views: 71

Answers (1)

vmp
vmp

Reputation: 2420

You are storing 8 in variable len, however your array has only 7 elements.

In the function, you have specified the first parameter incorrectly. Arrays are always passed by reference, you don't need a * and [], choose one.

void max_array (int *array, int len, int *max){
    for (int i = 0; i < len; ++i) {
        if (*max < array[i]){
            *max = array[i];
        }
    }
}

remember to alter the value in the len variable.

Upvotes: 2

Related Questions