编辑代码

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

struct Box {
    char key;
    int count;
};

struct Box* vote(char voter[][2], int numVoters, int* numBoxes) {
    // 初始化箱子数组
    struct Box* boxes = (struct Box*)malloc(numVoters * sizeof(struct Box));
    for (int i = 0; i < numVoters; ++i) {
        boxes[i].key = voter[i][0];
        boxes[i].count = 0;
    }

    // 统计每个箱子的票数
    for (int i = 0; i < numVoters; ++i) {
        for (int j = 0; j < numVoters; ++j) {
            if (voter[i][0] == boxes[j].key) {
                boxes[j].count += 1;
                break;
            }
        }
    }

    // 更新输出参数,即箱子的数量
    *numBoxes = numVoters;

    return boxes;
}

int main() {
    char voter[][2] = {
        {'a', 'b'},
        {'a'},
        {'b'},
        {'a'},
        {'b'},
        {'c'},
    };

    int numVoters = sizeof(voter) / sizeof(voter[0]);
    int numBoxes = 0;

    struct Box* boxes = vote(voter, numVoters, &numBoxes);

    // 打印结果
    for (int i = 0; i < numBoxes; ++i) {
        printf("Box %c: %d\n", boxes[i].key, boxes[i].count);
    }

    // 释放动态分配的内存
    free(boxes);

    return 0;
}