数组转换

数组和集合 / 数组

int twice(int x) {
    return x * 2;
}

//replaces every element with f(element), like map
void map(int arr[], size_t count, int (*f)(int)) {
    for (size_t i = 0; i < count; i++) {
        arr[i] = f(arr[i]);
    }
}

void printArray(const char *name, const int arr[], size_t count) {
    printf("%s is {", name);
    for (size_t i = 0; i < count; i++) {
        if (i > 0) {
            printf(", ");
        }
        printf("%d", arr[i]);
    }
    printf("}\n");
}

int numbers[] = {1, 2, 3, 4, 5};
size_t count = sizeof numbers / sizeof numbers[0];

//C has no map or comprehension: a loop changes the elements in place
for (size_t i = 0; i < count; i++) {
    numbers[i] *= 3;
}
//numbers is {3, 6, 9, 12, 15}
printArray("numbers", numbers, count);

map(numbers, count, twice);
//numbers is {6, 12, 18, 24, 30}
printArray("numbers", numbers, count);

//to another type: a new array of the size of the old one
double quarters[5];
for (size_t i = 0; i < count; i++) {
    quarters[i] = numbers[i] / 4.0;
}
//quarters is {1.5, 3, 4.5, 6, 7.5}
printf("quarters is {%g, %g, %g, %g, %g}\n",
       quarters[0], quarters[1], quarters[2], quarters[3], quarters[4]);