Home > Net >  Cannot call a function in a C program
Cannot call a function in a C program

Time:12-15

#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 100

void max_min(int arr[MAX_SIZE]) {
  int i, j;
//maximum loop below
  int max;
  max = arr[0];
  for (i = 0; i < sizeof(arr[i]);   i) {
    if ((arr[i]) > max) {
      arr[i] = max;
    }
    if ((arr[i]) < max) {
      break;
    }
  }
  printf("Largest = %d", max);
//minimum loop below
  int min;
  min = arr[0];
  for (j = 0; j < sizeof(arr[j]);   i) {
    if ((arr[j]) < min) {
      arr[j] = min;
    }
    if ((arr[j]) > min) {
      break;
    }
  }

int main(void) {
  int arr[MAX_SIZE];
  printf("Enter 10 elements for array > ");
  int i;
  for (i = 0; i < 10;   i) {
    scanf("%d", &arr[i]);
  }
  printf("Your array is: \n");
  for (i = 0; i < 10;   i) {
    printf("%d", arr[i]);
    printf(" ");
  }
  max_min(arr[MAX_SIZE]);
  return 0;
}

I am trying to write a min, max loop as I typed above. The problem is when I don't call function and enter 10 number inputs, the array print loop works fine and it takes an array. When I call array by max_min(arr[MAX_SIZE]); the array print loop stops working and the program doesn't go further. Appreciate any help.

CodePudding user response:

You just need to call your function with max_min(arr), not max_min(arr[MAX_SIZE]).

arr[MAX_SIZE] is trying to access the element at index 100 in your array, but valid indexes only range from 0 to 99.

Passing arr will pass the array pointer instead, which is what the function is expecting.

CodePudding user response:

If you indent your code you'll find that the max_min function is lacking the end }. Also, max_min(arr[MAX_SIZE]); is only sending in one int to the function (and it's out of bounds) - also sizeof(arr[i]); is not going to work and neither will sizeof(arr); since arrays decay into pointers to the first element when passed as arguments to functions. You need to send in the number of elements in the array as an argument to the function.

You assign arr[i] = max; and arr[i] = min; in your loops when it should be max = arr[i]; and min = arr[i];.

You are also using the wrong variable in for (j = 0; j < sizeof(arr[j]); i) (note the i which should be j).

Example fix:

#include <stddef.h>

void max_min(int arr[], size_t count) {
    int min = arr[0];
    int max = arr[0];
    for (size_t i = 1; i < count;   i) {
        if (arr[i] > max) max = arr[i];
        else if (arr[i] < min) min = arr[i];
    }
    printf("Smallest = %d\nLargest = %d\n", min, max);
}

And call it with:

max_min(arr, 10); // where 10 is the number of values the user has entered
  • Related