My program has 3 int arrays (pointers) declared in the main function. The user enters the length of array A
, which is then filled with random numbers.
Then, a function is called which takes all 3 arrays as its arguments. It takes all the even numbers from array A
and puts them into array B
, and all the odd numbers into C
. The sizes of B
and C
need to be the same as the number of their elements. The elements of B
are then printed.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int velA, velB, velC; //the sizes of all the arrays
void napravi(int a[], int *b, int *c);
void main() {
int *a, *b, *c;
int i;
srand(time(NULL));
printf("Enter array lenght:");
scanf("%d", &velA);
getchar();
a = (int*)calloc(velA, sizeof(int));
b = (int*)malloc(4); //I have to initialize the variable in order to pass it as an argument ?
c = (int*)malloc(4);
for(i = 0; i < velA; i++) {
a[i] = rand() %101;
}
napravi(a, b, c);
for(i = 0; i < velB; i++) {
printf("%d ", b[i]);
}
free(a);
// free(b); //Windows has triggered a breakpoint in .exe
// free(c);
getchar();
}
void napravi(int a[], int *b, int *c) {
int i;
int j = 0, k = 0;
for(i = 0; i < velA; i++) {
if(a[i] % 2 == 0) {
j++;
}
else {
k++;
}
}
free(b);
free(c);
b = (int*)calloc(j, sizeof(int));
c = (int*)calloc(k, sizeof(int));
j = 0; k = 0;
for(i = 0; i < velA; i++) {
if(a[i] % 2 == 0) {
b[j] = a[i];
// printf("\n%d | %d", a[i], b[j]);
j++;
}
else {
c[k] = a[i];
k++;
}
}
velB = j;
velC = k;
}
There are 2 problems with this code.
- First, if the user enters a value that is bigger than something around ~420, it starts to print junk values like -17987777...
- Second, when I attempt to free(b) and free(c) at the end, the program crashes with an error "Windows has triggered a breakpoint in my.exe".