Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers comparison

Tags:

c

pointers

I am writing a program that simulates the race between the tortoise and the hare.

They both move along two distinct one-dim array of 70 elements and, of course, since they move forward and backward they might wind up beyond the element 0 or 69.

I want to use pointers comparison to check if they did, so here comes the question:

I know that pointer comparison is legit if we are comparing pointers that point to elements of the same array, because otherwise we can't be sure of their position in memory. Still, suppose we have:

char arr[70];
char *p1 = &arr[0]
char *p2 = &arr[69]

Can't we be sure that p1 > p1 - 3 and p2 < p2 + 6 , because, in this case, the addresses will be contiguous? We know for certain which comes first and whatnot, right?

I did various tests and it appears to be so, but I wanted to be sure.

like image 300
Talete Avatar asked Jan 20 '26 20:01

Talete


1 Answers

No. It is only valid to compare pointers which point to an element within an array object or one past the end of the array object. But there is another problem here.

As they are defined above (p1 pointing to the first element of arr and p2 pointing to the last element of arr), you might think that attempting to dereference p1 - 3 or p2 + 6 would lead to undefined behavior; but even attempting to form the addresses p1 - 3 or p2 + 6 by using pointer arithmetic leads to undefined behavior, so the program is invalid the moment this pointer arithmetic is attempted. You can use pointer arithmetic to form an address that is within the array object, or one past the end of the array object. No other addresses may be formed from a pointer to an element of the array using pointer arithmetic.

like image 53
ad absurdum Avatar answered Jan 23 '26 11:01

ad absurdum