I have to write a function with the signature
int *greater (int n[], int length, int value)
that returns a pointer to an array containing the elements in n[] that are greater than a value. The array returned must be exactly the length to hold the values greater than value and have no unused elements.
I have the following code:
#include <stdio.h>
int k=0, v[100];
int * greater(int n[], int length, int value)
{
for (int i=0; i<length-1; i++)
if (n[i]>value)
{
v[k]=n[i];
k++;
}
int *p=v;
return p;
}
int main ()
{
int a[]={1,2,3,4,5};
int *p=greater (a,5,3);
int *end; end=v+k;
while (p<=end)
{
printf ("%i ", *p);
p++;
}
}
The problem is that p will only hold the value of 4, therefore it will print 4 0, instead of 4 5. Any ideas what I am doing wrong?
i<length-1-->i<lengthandwhile (p<=end)-->while (p<end)