I'm trying to learn using pointers, and in the code below I can send variables to a function.
But the return is obviously wrong and I can't seem to figure it out.
What I want the function to return is the number of even number occurrences.
Any suggestions to where I go wrong would be much appreciated.
I've tried to comment to indicate where I'm struggling, although I'm sure you would see it anyway.

``````#include <stdio.h>

int countEven (int* numbers)
{
int even[7];
int i=0, j=0;

for(i=0;i<7;i++)
{
if(numbers[i]%2 == 0)
{
even[j]=numbers[i];
j++;
}
}
printf ("%i\n", j);     //Checking if function works
return;
}

int main (void)
{
int numbers[] = {2, 5, 10, 16, 31, 17, 30};
int size=7;
int j=0;

countEven(&numbers);

printf ("%i\n", countEven(numbers)); //return output causing problems

system ("pause");
return 0;
}``````
3
Contributors
3
Replies
5
Views
7 Years
Discussion Span
Last Post by Pooch74

The main problem with your code is that the arrays should not be passed using the address operator (&). So if you wanted to pass the array to your `countEven` function, you'd use the following

``countEven(numbers);``

This is mainly because the name of the array is a pointer to its first element.

The second problem is that you've forgotten to put the j in your function's return statement.

Last but not least, the `size` and `j` variables inside `main` are not used, so you can get rid of them.

Here's how I'd write the above piece of code

``````#include <stdio.h>

int countEven (int *numbers)
{
int even[7];
int i=0, j=0;

for(; i < 7; ++i)
if(!(numbers[i] % 2))
even[j++]=numbers[i];

return j;
}

int main (void)
{
int numbers[] = {2, 5, 10, 16, 31, 17, 30};

countEven(numbers);

printf ("%d\n", countEven(numbers));

return 0;
}``````

Edited by creeps: n/a

Votes + Comments
there's a nice FOR loop.

Please note that the label 'numbers' is a pointer to the first element in the array numbers[]. So we can write your function call like below:

``````#include <stdio.h>

#define ARR_SIZE 7

int countEven (int* numbers)
{
int i = 0;

for (; i < ARR_SIZE; ++i)
fprintf(stdout, "ans->%d\n", *(numbers + i));
return 0;
}

int main (void)
{
int numbers[] = {2, 5, 10, 16, 31, 17, 30};

countEven(numbers);/*the array label numbers is a pointer to the first element of the array*/

return 0;
}``````

You should be able to figure the rest out.

Awesome guys! It works like a charm now.
Thanks a lot for the help, every bit of advice certanily gives me a better understanding of how to use pointers.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.