int *dynArr(int* arr, int n, int isEven) {
int count = 0;
int* t = (int*)calloc(n, sizeof(int));
assert(t);
if (isEven == 1) {
for (int i = 0; i < n; i ) {
if (arr[i] % 2 == 0) {
t[count ] = arr[i];
}
}
}
t = (int*)realloc(*t, count * sizeof(int));
return t;
}
void main() {
int a[] = { 1,8,3,6,11 };
int n = sizeof(a) / sizeof(int);
int isEven = 1;
int* arr = dynArr(a, n, isEven);
for (int i = 0; i < n; i ) {
printf("%d", arr[i]);
}
}
The problem is when I'm returning the array I don't get any output, When I'm debugging I get this error: "Unhandled exception at 0x7A08B54D (ucrtbased.dll) in homelab8.exe: 0xC0000005: Access violation reading location 0x00000004." Someone have an idea how do I fix this?
CodePudding user response:
First of all, you are passing a bad parameter to realloc
. This would easily have been caught had you been using your compiler's warnings.
The other major issue is that you are accessing n
elements of the array pointed by arr
, but it doesn't have n
elements.
Since you have two values to return, you will need to return through arguments (or return a struct).
// Returns 0 on success.
// Returns -1 and sets errno on error.
int filter_even_or_odd(
int **filtered_arr_ptr, // The address of a variable that accepts output.
size_t *filtered_n_ptr, // The address of a variable that accepts output.
int *arr,
size_t n,
int keep_even // Keep even or keep odd?
) {
size_t filtered_n = 0;
int *filtered_arr = malloc( sizeof(int) * n );
if (!filtered_arr)
return -1;
int to_keep = keep_even ? 0 : 1;
for ( size_t i = 0; i < n; i ) {
if ( arr[i] % 2 == to_keep ) {
filtered_arr[ filtered_n ] = arr[i];
}
}
int *tmp = realloc( filtered_arr, sizeof(int) * filtered_n );
if (tmp)
filtered_arr = tmp;
*filtered_arr_ptr = filtered_arr;
*filtered_n_ptr = filtered_n;
return 0;
}