小编Jes*_*ahm的帖子

如何在c中找到未知类型数组中的max元素(使用指向函数的指针)

我试图写一个通用的函数,即获得任何类型的数组(int,float,string)并返回它的最大元素(如果它是一个字符串数组-然后词典编纂).我设法编译它,但是当我运行它时,我得到了segmentation fault (core dumped).谁能告诉我我的代码有什么问题?

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

void *maxElement(void **arr, int size, int(*comp)(void*, void*)) {
    int i = 0;
    void *max = NULL;

    for (i = 0; i < size; i++) {
        if (comp(arr[i], arr[i + 1])) {
            max = (void*)arr[i];        
        } else
            max = (void*)arr[i + 1];
    }
    return (void*)max;
}

int compareInt(void *a, void *b) {
    int *temp_a = (int*)a, *temp_b = (int*)b;

    if (*temp_a > *temp_b)
        return 1; …
Run Code Online (Sandbox Code Playgroud)

c arrays algorithm pointers function

2
推荐指数
1
解决办法
222
查看次数

标签 统计

algorithm ×1

arrays ×1

c ×1

function ×1

pointers ×1