Reputation: 112
this function is supposed to store odd numbers between l
and r
inclusive in an array of ints. result_count
is for
result_count
variableI don't know what to do inside the if condition. I tried this:
int* oddNumbers(int l, int r, int* result_count)
{
int i;
for (i = l; i <= r; i++)
{
if (i%2 == 1)
{
i = result_count[i];
}
}
return result_count;
}
Upvotes: 0
Views: 4123
Reputation: 154127
@J. Doe good answer had some issues with edge and extreme cases the following addresses.
#include <stdlib.h>
// Return the list of odd numbers and a count.
// With oddNumbers(INT_MIN, INT_MAX,...) the number of odd integers is INT_MAX + 1,
// the result_count is saved as some type that supports value INT_MAX + 1
// such as usually `unsigned`.
int *oddNumbers(int l, int r, unsigned* result_count) {
// if l is even, start at l = l + 1
// Cannot overflow as INT_MAX is odd
l += !(l % 2);
// The list is empty when left/right out of order.
if (l > r) {
*result_count = 0;
return NULL;
}
// if r is even, end at r = r - 1
// When r even, decrement cannot overflow as r > INT_MIN due to prior code
r -= !(r % 2);
// allocate
*result_count = ((unsigned) r - l) / 2 + 1;
int *result = malloc(sizeof *result * *result_count);
if (result == NULL) {
return NULL;
}
// fill it
result[0] = l;
for (unsigned i = 1; i < *result_count; i++) {
l += 2; // do not add 2 until needed
result[i] = l;
// Adding +2 afterward risks UB of `INT_MAX + 2`.
}
return result;
}
Upvotes: 1
Reputation:
- Store the size of the array to be returned in the
result_count
variable- Allocate the array statically or dynamically.
I go for a dynamically allocated array.
#include <limits.h>
#include <stdlib.h>
#include <assert.h>
int* oddNumbers(int l, int r, int* result_count)
{
int *result;
int i;
assert(result_count && l <= r && INT_MIN < r);
l += !(l % 2); // if l is even start at l = l + 1
r -= !(r % 2); // if r is even end at r = r - 1
*result_count = (r - l) / 2 + 1; // calculate array size
result = malloc(*result_count * sizeof(*result));
if(!result)
return NULL;
// fill it
for (i = 0; l <= r; ++i, l += 2)
result[i] = l;
return result;
}
#include <stdio.h>
int main(void)
{
int min = 42;
int max = 85;
int count;
int *numbers = oddNumbers(min, max, &count);
int i;
if(count && !numbers) {
printf("There are %d odd numbers between %d and %d, "
"but not enough memory to allocate an array of that size :(\n\n",
count, min, max );
return EXIT_FAILURE;
}
printf("Number count: %d\n", count);
for (i = 0; i < count; ++i)
printf("%d ", numbers[i]);
putchar('\n');
free(numbers);
return 0;
}
Don't forget to free()
the returned pointer when you are done using it.
Upvotes: 3