通过函数指针实现多态,注册回调函数的方式

void printAllArray(void* arr, int eleSize, int len, void(*myPrint)(void*)){
    char* arrStart = (char*)arr;
    for(int i = 0; i < len; ++i){
        char* eleStart = arrStart + i * eleSize;
        myPrint(eleStart);
    }
    printf("\n");
}
void printInt(void* data){
    int* ele = (int*)data;
    printf("%d ", *ele);
}
struct Person{
    char name[64];
    int age;
};
void printPerson(void* data){
    struct Person* ele = (struct Person*)data;
    printf("Name: %s, Age: %d \n", ele->name, ele->age);
}
int main()
{
    int arr[] = {1, 2, 3, 4, 5};
    printAllArray(arr, sizeof(int), 5, printInt);

    struct Person personArr[] = {
        {"aaa", 20},
        {"bbb", 30},
        {"ccc", 40},
        {"ddd", 50},
        {"eee", 60},
    };
    printAllArray(personArr, sizeof(struct Person), 5, printPerson);
    
    return 0;
}

输出:

1 2 3 4 5 
Name: aaa, Age: 20 
Name: bbb, Age: 30 
Name: ccc, Age: 40 
Name: ddd, Age: 50 
Name: eee, Age: 60