Char C pointer arithmetic
The result, as you presented the question, is undefined. For the pointer to work correctly, they must be from the same sequence of arrays (dynamic, automatic, and even automatic VLA doesn't matter). or one past address after the last element:
Β§6.5.6 Additive operators (p9)
When two pointers are subtracted, both must point to elements of the same array object, or one after the last element of the array object ; the result is the difference between the indices of the two array elements. The size of the result is implementation-defined, and its type (signed integer type) is
ptrdiff_t
as defined in the header<stddef.h>
. If the result is not represented in an object of this type, the behavior is undefined. In other words, if the expressionsP
andQ
point to the elementsi-th
and thej-th
array object, respectively , the expression(P)-(Q)
has the value ij if the value fits into an object of typeptrdiff_t.
In addition, if the expressionP
points either to an element of the array object or past the last element of the array object, and the expressionQ
points to the last element of the same array object, the expression((Q)+1)-(P)
has the same meaning as((Q)-(P))+1
, and how-((P)-((Q)+1))
, and has a value of 0 if the expressionP
points one after the last element of the array object, although the expression(Q)+1
does not point to an element of the array object. 106
However, if you've paraphrased to fit the rules above, something like:
#include <stdio.h>
int main()
{
const char *p = "Hello World";
const char *q = p+7;
printf("%td\n", q-p);
return 0;
}
Output
7
and the reason is explained from the given part of the standard.
source to share
Edited
The answer to this question depends on the situation.
1) In your situation, since pointers do not point to anything, the result will be garbage
2) If the two pointers point to two valid memory locations in program space, then the result is the number of bytes of memory between the two locations. Although it doesn't make any sense, and it's UB according to the C Spec, unless the two pointers point to the same array or string. If two pointers point to the same array or string, the result is the number of elements between the two elements in the same array (when the pointers point to these two elements within that array). Check out this SO question for examples and explanations.
source to share