我试图写一个通用的函数,即获得任何类型的数组(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)