You are thrown off by the line number reported by the compiler. The "incorrect initializer" message refers to the whole DATA result = bsearch(...)
initialization/expression, which ends with the last argument, and not to the last argument itself.
Initializer is incorrect because result
is declared as DATA
(a struct), and bsearch
returns a pointer. To fix it, declare result
as a pointer:
DATA *result = bsearch(
searchData,
data_array,
m_arrayLength,
sizeof(DATA),
CompareDataByKey);
When you fix that, you must also change FindDataByKey
to return DATA *
, not DATA
. Several unrelated coding remarks:
You don't need to
malloc
the search data when callingbsearch
, you can just initialize it on the stack and pass the address of the variable to the function. For example:DATA searchData; searchData.key = key; return bsearch(&searchData, ...);
If you call
malloc
, don't forget to check its return value. A call tomalloc
can fail, and it is a good idea to report this failure to the user. (The customary way of doing that is by creating a wrapper called something likexmalloc
, which callsmalloc
, checks its result, and prints an error message and callsexit()
if the result is NULL.)Prefixing a global variable with
m_
will confuse users coming from a C++ background, where them_
prefix denotes class members.