好的,所以我在业余时间尝试构建一些函数库来娱乐,并且我正在自学函数指针。我尝试制作一个 binary_search 函数来查找项目数组中最旧的项目。我知道该算法有效,但我无法克服这个错误。由于某种原因,当我的代码进入函数指针时,它停止执行并死掉......我做了一些测试,当我的代码进入strvoidcmp
时,我喂它的两个void *
s 是空的......
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "algorithms.h"
void generate_array(char (*partial_list)[10]){
size_t j = 0, i = 0;
for(j = 0; j < 20; j++){
for(i = 0; i < 10; i++){
partial_list[i][j] = 0;
}
}
for(i = 0; i < 11; i++){
memcpy(partial_list[i], "is there", 9);
}
for(i = 0; i < 9; i++){
memcpy(partial_list[i], "not there", 10);
}
}
void LMERROR(char *msg){
fprintf(stderr, msg);
fflush(stderr);
}
int binary_search_top(void **list, const int size, void *value, int (*compare)(void *, void *)){
size_t hi = 0;
size_t lo = 0;
size_t mid = 0;
size_t found = 0;
if(list == NULL){
LMERROR("NULL found in function binary_search");
return -1;
}
hi = size;
printf("test: %s\n", (char *)value);
while(lo < hi){
mid = ceil((hi - lo) / 2 + lo);
printf("test: %d\n", mid);
if(compare(list[mid], value)){
hi = mid - 1;
printf("test1\n");
}else{
lo = mid;
found = mid;
printf("test2\n");
}
}
printf("exiting");
return found;
}
int strvoidcmp(void *p1, void *p2){
printf("testing: %s, %s\n", (char *)p1, (char *)p2);
return strcmp((char *)p1, (char *)p2);
}
int main(){
int (*compare)(void *, void *);
char partial_list[20][10];
const size_t length = 20;
char value[] = "is there";
int ret = 0;
compare = strvoidcmp;
printf("test: %d\n", ret);
generate_array(partial_list);
printf("test: %d\n", ret);
ret = binary_search_top((void **)partial_list, length, value, compare);
printf("test: %d\n", ret);
return 0;
}