Is it possible, for a pointer variable p, that p<(p+1) is false? Please explain your answer. If yes, under which circumstances can this happen?
I was wondering whether p+1 could overflow and be equal to 0.
E.g. On a 64-bit PC with GCC-4.8 for a C-language program:
int main(void) { void *p=(void *)0xFFFFFFFFFFFFFFFF; printf("p :%p\n", p); printf("p+1 :%p\n", p+1); printf("Result :%d\n", p<p+1); }
It returns:
p : 0xffffffffffffffff p+1 : (nil) Result : 0
So I believe it is possible for this case. For an invalid pointer location it can happen. This is the only solution I can think of. Are there others?
Note: No assumptions are made. Consider any compiler/platform/architecture/OS where there is a chance that this can happen or not.
For example, if p is a pointer to an integer, the following code is invalid: p = 0; *p = 12; There is no block pointed to by p. Therefore, trying to read or write anything from or to that block is an invalid zero pointer reference.
The syntax of declaring a pointer is to place a * in front of the name. A pointer is associated with a type (such as int and double ) too. Naming Convention of Pointers: Include a " p " or " ptr " as prefix or suffix, e.g., iPtr , numberPtr , pNumber , pStudent .
No, a single pointer can only point to one thing.
You need to initialize a pointer by assigning it a valid address. This is normally done via the address-of operator (&). The address-of operator (&) operates on a variable, and returns the address of the variable. For example, if number is an int variable, &number returns the address of the variable number.
Is it possible, for a pointer variable
p
, thatp<(p+1)
is false?
If p
points to a valid object (that is, one created according to the C++ object model) of the correct type, then no. p+1
will point to the memory location after that object, and will always compare greater than p
.
Otherwise, the behaviour of both the arithmetic and the comparison are undefined, so the result could be true, false, or a suffusion of yellow.
If yes, under which circumstances can this happen?
It might, or might not, happen with
p = reinterpret_cast<char*>(numeric_limits<uintptr_t>::max);
If pointer arithmetic works like unsigned integer arithmetic, then this might cause a numeric overflow such that p+1
has the value zero, and compares less than p
. Or it might do something else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With