我在使用此代码的lfind调用中遇到了分段错误。 CVector是一个带有名为elems的数组的结构。我知道CVectorCreate和CVectorAppend函数有效。第一个块是测试代码,它是作为类的一部分提供的,不能更改,第二个是我编写的函数调用。有人可以帮我识别我的问题吗?谢谢!
char *jumbled = "xatmpdvyhglzjrknicoqsbuewf";
CVector *cv = CVectorCreate(sizeof(char), 4, NULL);
for (int i = 0; i < strlen(jumbled); i++)
CVectorAppend(cv, &jumbled[i]);
printf("\nDoing linear searches on unsorted cvector.\n");
char ch = '*';
Verify(0, CVectorSearch(cv, &jumbled[0], CmpCharElem, 0, false), "Linear search");
int CVectorSearch(const CVector *cv, const void *key, CVectorCmpElemFn cmpfn, int startIndex, bool isSorted)
{
assert(startIndex >= 0 && startIndex <= cv->logicalLength);
void *found = NULL;
if (isSorted == true) {
found = bsearch(key, (char *)(cv->elems) + (startIndex * cv->elemSize),
cv->logicalLength, cv->elemSize, cmpfn);
} else {
found = lfind(key, (char *)(cv->elems) + (startIndex * cv->elemSize), cv->logicalLength, cv->elemSize, cmpfn);
}
答案 0 :(得分:1)
与bsearch
不同,lfind
的第三个参数是指针。
size_t nmemb = cv->logicalLength;
found = lfind(key, (char *)(cv->elems) + (startIndex * cv->elemSize),
&nmemb, cv->elemSize, cmpfn);