该函数应该在一个整数数组中存储l
和r
之间的奇数。 result_count
用于
result_count
变量中我不知道在if条件下该怎么做。我尝试过:
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;
}
答案 0 :(得分:3)
- 将要返回的数组的大小存储在
result_count
变量中- 静态或动态分配数组。
我去寻找动态分配的数组。
#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;
}
在使用完返回的指针后,请不要忘记free()
。
答案 1 :(得分:1)
@J. Doe的好答案是以下情况中的极端情况和极端情况。
#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;
}