开发者

Binary search for specific value in array of structs

I wrote this function that uses a binary search to look for a specific value in an array of structs. Why doesn't it compile?

I'm get开发者_运维技巧ting this error:

prog.c:224: error: subscripted value is neither array nor pointer
prog.c:226: error: subscripted value is neither array nor pointer

This is the function:

int FieldSearch(Field *pArr, int size, int val)
{
    int low=0,high=size-1, middle;
    while (low <= high)
    {
        middle = (low + high)/2;
        if (val == pArr->Id[middle])
            return middle;
        else if (val < pArr->Id[middle])
            high = middle -1;
        else
            low = middle +1;
    }
    return NOT_FOUND;
}

This is the field struct:

typedef struct field
{
        char Id;
        Coordinates location;
        int area;
        int price;
} Field;

Maybe the prototype is wrong...


Your problem is this statement:

pArr->Id[middle]

It looks like, but I don't have nearly enough info, that your member Id is not a pointer or an array, but merely a variable. So you cannot access it with an operator[]. You should show us what this Field object looks like.

I'm guessing you should do something like this

(pArr + middle)->Id so this will access the element of the Field array you passed into your function. Then you do have to pass in an actual array of Field structures, for this to work.


If you want to search the "array" pArr, you need to put the brackets directly behind the identitifier. This should work:

pArr[middle].Id
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜