1

I'm writing a vector in C. The CVectorSearch function uses bsearch if it's sorted, and lfind if it's unsorted. Why am I getting the warning "assignment makes pointer from integer without a cast" when I'm calling lfind? It seems to work fine even when lfind is being used.

typedef struct
{
  void *elements;
  int logicalLength;
  int allocatedLength;
  int elementSize;
} CVector;

typedef void (*CVectorFreeElemFn)(void *elemAddr);


int CVectorSearch(const CVector *v, const void *key, 
          CVectorCmpElemFn comparefn, 
          int startIndex, bool isSorted)
{

    void * found;
    int elemSize = v->elementSize;
    int length = v->logicalLength;
    void *startAddress = (char*)v->elements + startIndex*elemSize;

    if(isSorted)
        found = bsearch(key, startAddress, length, elemSize, comparefn);
    else
        found = lfind(key, startAddress,  &length,  elemSize, comparefn);


    if(found)
        return ((char*)found - (char*)v->elements) / elemSize;
    else
        return -1;
}

edit: Now that I've included search.h I'm getting:

warning: passing argument 3 of 'lfind' from incompatible pointer type

The program is still working correctly, though.

alk
  • 69,737
  • 10
  • 105
  • 255

3 Answers3

4

Have you included <search.h> which defines lfind? If a function is called without a prototype, your compiler may assume it returns int.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
1

The third argument to lfind() is a pointer to size_t not int as you are passing. The size_t type may be of a different size than int on some architectures (particularly x86-64) and it is also unsigned. You have to change the type of the length variable.

Juliano
  • 39,173
  • 13
  • 67
  • 73
0

I don't think the above questions really solve the issue as I had this problem. The true answer I believe is the distinction between bsearch prototype and lfind prototype. Let's takea look

 void *bsearch(const void *key, const void *base, size_t nmemb,
              size_t size, int (*compar)(const void *, const void *));

Versus

void *lfind(const void *key, const void *base, size_t *nmemb,
              size_t size, int(*compar)(const void *, const void *));

If you'll notice that the third parameter of the lfind function is a pointer to a size_t type not (as in the bsearch function ) a direct copied value.

Just make sure you pass in the address of the size and it'll be fine.

Vivek
  • 621
  • 7
  • 18