1

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 getting 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...

1
  • id is integer i mean %d, yes this is c... Commented Jun 4, 2011 at 9:11

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

this is the field struct: typedef struct field { char Id; Coordinates location; int area; int price; } Field;
Id is not an array, you cannot access it with the operator[], as I said
1

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

pArr[middle].Id

1 Comment

ok that seem to work.. i guess that problem was that i didn't put the brackets at right place..this is the fix line if (val == pArr[middle].Id) return middle; else if (val < pArr[middle].Id) thnx guys!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.