PoorProgrammer
PoorProgrammer

Reputation: 111

Function to check all elements of an array

I want to make a function to check all elements of an array. But how to pass an array as parameter of a function correctly? I've tried to pass a pointer but it doesn't work, compiler don't even want to compile that code. What am I doing wrong? Please help!

#include <stdio.h>

#define N 10

int iseven(int *A); // prototype

int main(void)
{
  int i;

  int A[N]; // array to check

  for (i = 0; i < N; i++)
    scanf("%d", &A[i]);

  i = iseven(*A);

  if (i == 1)
    printf("All numbers are even!\t\n");
  else
    printf("Not all numbers are even!\t\n");

  return 0;
}

int iseven(int *A)
{
  int i;
  int flag = 1;

  for (i = 0; i < N; i++)
    if (((A[i] % 2) == 0) && (A[i] >= 2))
      continue;
    else
    {
      flag = 0;
      break;
    }

  return flag;
}

gcc array.c -o array.exe

 array.c: In function 'main':
 array.c:16:14: warning: passing argument 1 of 'iseven' makes pointer from integer without a cast [-Wint-conversion]
        i = iseven(*A);
                   ^
 array.c:5:5: note: expected 'int *' but argument is of type 'int'
 int iseven(int *A); // array to check
     ^

Upvotes: 0

Views: 969

Answers (1)

GoodDeeds
GoodDeeds

Reputation: 8507

You need to call the function in the form

i = iseven(A);

Using i = iseven(*A); means that you are dereferencing the value at address A and passing it, which effectively means you are passing the first element of the array to the function.

This is the reason the compiler complains that the function receives an int when it was expecting an int*

Upvotes: 4

Related Questions