谁能告诉我为什么下面代码中的 bsearch() 在列表中找不到项目“getwidth”?我尝试了几个编译器,但它们都不适用,所以它一定是我的代码中的一个错误。但是,我真的不明白那里有什么问题。传递给 bsearch() 的回调总是返回 != 0 但仍然只调用 5 次,然后 bsearch() 返回 NULL,尽管它没有遍历所有项目。这是为什么?
这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
typedef struct wxLuaBindMethod
{
const char *name;
int method_type;
void *wxluacfuncs;
int wxluacfuncs_n;
void *basemethod;
} wxLuaBindMethod;
#define WXLUAMETHOD_CONSTRUCTOR 0x0001
#define WXLUAMETHOD_METHOD 0x0002
#define WXLUAMETHOD_DELETE 0x2000
wxLuaBindMethod wxSize_methods[] = {
{ "DecBy", WXLUAMETHOD_METHOD, NULL, 1, NULL},
{ "DecTo", WXLUAMETHOD_METHOD, NULL, 1, NULL},
{ "GetHeight", WXLUAMETHOD_METHOD, NULL, 1, NULL},
{ "GetWidth", WXLUAMETHOD_METHOD, NULL, 1, NULL},
{ "IncBy", WXLUAMETHOD_METHOD, NULL, 1, NULL},
{ "IncTo", WXLUAMETHOD_METHOD, NULL, 1, NULL},
{ "IsFullySpecified", WXLUAMETHOD_METHOD, NULL, 1, NULL},
{ "Scale", WXLUAMETHOD_METHOD, NULL, 1, NULL},
{ "Set", WXLUAMETHOD_METHOD, NULL, 1, NULL},
{ "SetDefaults", WXLUAMETHOD_METHOD, NULL, 1, NULL},
{ "SetHeight", WXLUAMETHOD_METHOD, NULL, 1, NULL},
{ "SetWidth", WXLUAMETHOD_METHOD, NULL, 1, NULL},
{ "delete", WXLUAMETHOD_METHOD|WXLUAMETHOD_DELETE, NULL, 1, NULL},
{ "op_add", WXLUAMETHOD_METHOD, NULL, 1, NULL},
{ "op_div", WXLUAMETHOD_METHOD, NULL, 1, NULL},
{ "op_eq", WXLUAMETHOD_METHOD, NULL, 1, NULL},
{ "op_iadd", WXLUAMETHOD_METHOD, NULL, 1, NULL},
{ "op_idiv", WXLUAMETHOD_METHOD, NULL, 1, NULL},
{ "op_imul", WXLUAMETHOD_METHOD, NULL, 1, NULL},
{ "op_isub", WXLUAMETHOD_METHOD, NULL, 1, NULL},
{ "op_mul", WXLUAMETHOD_METHOD, NULL, 1, NULL},
{ "op_ne", WXLUAMETHOD_METHOD, NULL, 1, NULL},
{ "op_set", WXLUAMETHOD_METHOD, NULL, 1, NULL},
{ "op_sub", WXLUAMETHOD_METHOD, NULL, 1, NULL},
{ "wxSize", WXLUAMETHOD_CONSTRUCTOR, NULL, 1, NULL},
{ 0, 0, 0, 0 },
};
int wxLuaBindMethod_CompareByNameFnGet(const void *p1, const void *p2)
{
int v = strcasecmp(((const wxLuaBindMethod*)p1)->name, ((const wxLuaBindMethod*)p2)->name);
printf("CMP: %s = %s? --> %d\n", ((const wxLuaBindMethod*)p1)->name, ((const wxLuaBindMethod*)p2)->name, v);
return v;
}
int main(int argc, char *argv[])
{
wxLuaBindMethod methodItem = { "getwidth", 10, 0, 0, 0 };
wxLuaBindMethod *wxlMethod;
wxlMethod = (wxLuaBindMethod *)bsearch(&methodItem, wxSize_methods, 25, sizeof(wxLuaBindMethod), wxLuaBindMethod_CompareByNameFnGet);
printf("RESULT: %p\n", wxlMethod);
return 0;
}
这是该程序生成的输出:
CMP: getwidth = delete? --> 3
CMP: getwidth = op_isub? --> -8
CMP: getwidth = op_iadd? --> -8
CMP: getwidth = op_div? --> -8
CMP: getwidth = op_add? --> -8
RESULT: 0x0
我真的不明白为什么它不起作用,尽管它实际上只有几行。有人可以对这种奇怪的行为有所了解吗?谢谢!