I was asked to define a function takes in the values of a list and distributes its elements into two lists: one meant for the odd numbers and the other for the even. I have created the function array_oddeven() and passed it two parameters:
int *ptr : a pointer to the array
int length : represents the size of the array
and called it inside int main()
This is my code :
#include <stdio.h>
#include <stdlib.h>
#define UPPER_BOUND 8
#define MAX  100
#define SIZE  12
void array_print(int *ptr, int length) {
    for (int i = 0; i < length; i++) {
        printf("%d ", ptr[i]);
    }
    printf("\n");
}
int* array_create(int length) {
    int *t = (int*)malloc(length * sizeof(int));
    for (int i = 0; i < length; i++) {
        t[i] = rand() % MAX;
    }
    return t;
}
int *array_oddeven(int *ptr, int length){
    int *even = (int*)malloc(length * sizeof(int));
    int *odd = (int*)malloc(length * sizeof(int));
    int j=0;
    int k=0;
    for (int i = 0; i < length; i++)
    {
        if (ptr[i] % 2 == 0) {
            even[j] = ptr[i];
            j++;
        } else {
            odd[k] = ptr[i];
            k++;
        }
    } 
    return even, odd;
}
int main()
 {
    int *t = array_create(SIZE);
    int *even = array_oddeven(t, SIZE);
    int *odd = array_oddeven(t, SIZE);
    array_print(t, SIZE);
    array_print(even, SIZE);
    array_print(odd, SIZE);
    free(odd);
    free(even);
    free(t);
    return 0;
}
I was expecting this result :
83 86 77 15 93 35 86 92 49 21 62 27 
83 77 15 93 35 49 21 27 
86 86 92 62
But I got this output instead :
83 86 77 15 93 35 86 92 49 21 62 27 
83 77 15 93 35 49 21 27 0 0 0 0 
83 77 15 93 35 49 21 27 0 0 0 0 
Where is my mistake?
 
     
    