I was playing around with pointer arithmetic and came across two rules in C Standard regarding pointer subtraction and comparison.
Rule 1: When two pointers are subtracted, both must point to elements of the same array object or just one past the last element of the array object (C Standard, 6.5.6); the result is the difference of the subscripts of the two array elements. Otherwise, the operation is undefined behavior (48).
Rule 2: Similarly, comparing pointers using the relational operators <, <=, >=, and > gives the positions of the pointers relative to each other. Pointers that do not point to the same aggregate or union (nor just beyond the same array object) are compared using relational operators (6.5.8). Otherwise, the operation is undefined behavior (53).
Subtracting or comparing pointers that do not refer to the same array is undefined behavior.
Question 1: As per rule 1 mentioned above, the behavior is undefined, but the program does print an address as output. The program crashes when I try to dereference the the variable containing the address. How come there is an address which exists but the value the address points to does not exist?
Question 2: As per rule 2 mentioned above, using relational operator to compare two pointers which refer two different arrays is undefined behavior, the program should crash, but I end up with an output? How is that possible?
Can someone please help me regarding this rule confusion? I have posted the code below:
#include <stdio.h>
int main()
{
char *pointer_1;
char *pointer_2;
char *difference;
int counter=0;
char string[20]={"Pointer Arithmetic"};
char str[30]={"Substraction and Comparison"};
pointer_1=string;
pointer_2=str;
difference=(char *)(pointer_2-pointer_1);
printf("%p\n",difference); Address exists
/*printf("%c\n",difference);*/ Dereferencing leads to program crash
while(pointer_1>pointer_2) Is one is allowed to use relational operators on
pointers which point to two different arrays?
{
{
counter++;
pointer_2++;
}
}
printf("%d",counter);
}