The program must divide the array into two arrays containing its even and odd values. Works on small values, up to 10, then gives out nonsense, please tell me what is the error?

#include <stdio.h> #include <malloc.h> #include <stdlib.h> void append (int *arr, int *len, int elem) { arr = realloc(arr, (*len + 1) * sizeof(int)); arr[*len] = elem; *len = *len + 1; } int main() { int len_ch = 0; int *ch = NULL; ch = malloc(len_ch * sizeof(int)); int len_nch = 0; int *nch = NULL; nch = malloc(len_nch * sizeof(int)); int N; int elem; scanf("%d", &N); int a[N]; for (int i = 0; i < N; i++) { scanf("%d", &a[i]); //a[i] = 0 + rand() % 20; } for (int i = 0; i < N; i++) { if (a[i] % 2 == 0) { append(ch, &len_ch, a[i]); } else { append(nch, &len_nch, a[i]); } } for (int i = 0; i < N; i++) { printf("%d ", a[i]); } printf("\nEVEN: "); for (int i = 0; i < len_ch; i++) { printf("%d ", ch[i]); } printf("\nODD: "); for (int i = 0; i < len_nch; i++) { printf("%d ", nch[i]); } printf("\n"); } 
  • one
    What do you mean by crap? - iluxa1810
  • Show what is in the input and output in the case of "nonsense" - nick_n_a
  • @nick_n_a Returns values ​​that I did not enter, or zeros. - Teofelts

1 answer 1

Well, see for yourself:

 void append (int *arr, int *len, int elem) { arr = realloc(arr, (*len + 1) * sizeof(int)); 

but this new value of the pointer remains local in the function, and when it leaves it is safely lost ...

Need to

 void append (int **arr, int *len, int elem) { *arr = realloc(*arr, (*len + 1) * sizeof(int)); 

Well and, accordingly, to transfer in function the pointer on a variable - type

 append(&ch, &len_ch, a[i]); 
  • Then adding an element to the end of the array will look like *arr[*len] = elem ; ? - Teofelts
  • (*arr)[*len] = elem; - what you wrote is the assignment of the elem to the address in arr[*len] :) - Harry
  • Thanks a lot! Gone to learn signs) - Teofelts