#include <stdio.h>
#include <stdlib.h>

int* odd_array(int arr[], int size, int* odd_size) {
    int* odd_arr = NULL;  // 奇数数组
    int count = 0;  // 计数器,记录奇数个数
    for (int i = 0; i < size; ++i) {
        if (arr[i] % 2 != 0) {  // 判断是否为奇数
            ++count;  // 奇数个数加1
        }
    }
    *odd_size = count;  // 将奇数个数传出
    odd_arr = (int*)malloc(count * sizeof(int));  // 分配奇数数组内存
    count = 0;  // 重置计数器
    for (int i = 0; i < size; ++i) {
        if (arr[i] % 2 != 0) {  // 判断是否为奇数
            odd_arr[count++] = arr[i];  // 将奇数放入奇数数组中
        }
    }
    return odd_arr;  // 返回奇数数组
}

int main() {
    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int size = sizeof(arr) / sizeof(arr[0]);
    int odd_size = 0;  // 奇数个数
    int* odd_arr = odd_array(arr, size, &odd_size);  // 获取奇数数组
    printf("Odd array: ");
    for (int i = 0; i < odd_size; ++i) {
        printf("%d ", odd_arr[i]);  // 输出奇数数组
    }
    free(odd_arr);  // 释放奇数数组内存
    return 0;
}
C语言实现数组奇数筛选:高效代码示例

原文地址: https://www.cveoy.top/t/topic/nBPL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录