C dynamic memory allocation array -
my program has 3 int arrays (pointers) declared in main function. user enters length of array a
, filled random numbers.
then, function called takes 3 arrays arguments. takes numbers array a
, puts them array b
, , odd numbers c
. sizes of b
, c
need same number of elements. elements of b
printed.
#include <stdio.h> #include <stdlib.h> #include <time.h> int vela, velb, velc; //the sizes of 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(); = (int*)calloc(vela, sizeof(int)); b = (int*)malloc(4); //i have initialize variable in order pass argument ? c = (int*)malloc(4); for(i = 0; < vela; i++) { a[i] = rand() %101; } napravi(a, b, c); for(i = 0; < velb; i++) { printf("%d ", b[i]); } free(a); // free(b); //windows has triggered breakpoint in .exe // free(c); getchar(); } void napravi(int a[], int *b, int *c) { int i; int j = 0, k = 0; for(i = 0; < 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; < 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 2 problems code.
- first, if user enters value bigger around ~420, starts print junk values -17987777...
- second, when attempt free(b) , free(c) @ end, program crashes error "windows has triggered breakpoint in my.exe".
try this
int main(void) { int *a, *b, *c; int i; srand(time(null)); printf("enter array lenght:"); scanf("%d", &vela); getchar(); = (int*)calloc(vela, sizeof(int)); //b = null;//there no need set value //c = null;//null better malloc(4) for(i = 0; < vela; i++) { a[i] = rand() %101; } napravi(a, &b, &c); for(i = 0; < velb; i++) { printf("%d ", b[i]); } free(a); free(b); free(c); getchar(); return 0; } void napravi(int a[], int **b, int **c) { int i; int j = 0, k = 0; *b = *c = null; velb = velc = 0; if(a == null || vela == 0) return; for(i = 0; < vela; i++) { if(a[i] % 2 == 0) { j++; } } if(velb = j) *b = (int*)malloc(velb * sizeof(int)); if(velc = vela - velb) *c = (int*)malloc(velc * sizeof(int)); j = 0; k = 0; for(i = 0; < vela; i++) { if(a[i] % 2 == 0) (*b)[j++] = a[i]; else (*c)[k++] = a[i]; } }
Comments
Post a Comment