This is what I made:
#include <stdio.h>
#include <stdlib.h>
int betweenArray(int a, int b){
int *arr,i,range;
range = b - a + 1;
arr = (int *)malloc(range*sizeof(int));
for(i=0;i<range;i++){
arr[i] = a++;
}
return * arr;
int main (int argc, const char * argv[]) {
int a,b,i;
int range;
printf("Give numbers: ");
scanf("%d %d",&a,&b);
range = b - a + 1;
for(i=0;i<range;i++)
printf("%d\n",betweenArray(a,b));
return 0;
}
So when I run this and give for example 2 and 5 as arguments I get as a result: 2 2 2 2 instead of 2 3 4 5. I can’t find where I made my mistake.
The problem is that you’re calculating the sequence, but you only return the first number of it.
The return value of
betweenArrayisintinstead ofint *and you doreturn * arr;instead ofreturn arr;. After fixing that, inmain, you would need to do:But it would be better if the function would return the array and the number of elements in it, for example like that: