Orisgeinkras
Orisgeinkras

Reputation: 3

Finding the value of the next iteration of an array pointer in C

Normally, when trying to reference the value of a pointer, one would use &p for the pointer p, so if I have a for loop that iterates through p, a pointer that points to an array, and I want to compare the value of p to that of p+1 I've ran into a bit of an issue. When I type

if(&p < &(p+1){
   foo();
}

and in response, I get this error:

error: lvalue required as unary '&' operand

It's worth noting I'm using C89 and the assignment I'm doing doesn't allow me to access the array values directly with arr[value], it's unfortunately required for what I'm writing this for. How do I go about accessing the value of p+1?

Upvotes: 0

Views: 611

Answers (2)

secuman
secuman

Reputation: 539

You must use the *p instead &p if you are going to reference the value of pointer 'p'. The '&' operand is the address of 'p', not a value. So, you must do like this:

if (*p < *(p + 1)){
    foo();
}

I suggest one sample below

void foo()
{
    printf("foo\n");
}

int main() 
{
    int arr[5] = {1, 2, 3, 4, 5} ;
    int * p = arr;

    for (int i = 0; i < 4; i++)
    {
        if (*p < *(p + 1))
        {
            foo();
        }
        p++;
    }

    return 0;
}

Upvotes: 0

Barmar
Barmar

Reputation: 781141

The & operator returns the address of its operand. You want the value, which is the * operator for dereferencing.

if (*p < *(p+1)) {
    foo();
}

Of course, you have to ensure that you don't do this when p points to the last element of the array, since p+1 points outside the array.

Upvotes: 4

Related Questions