I know that pointers (to array element) and iterators can be incremented/decremented to walk a sequence of elements and can jump back-and-for elements in the sequence.
But what will happen if I increment a pointer to a single object or add to it an integer value? is it undefined behavior or it is OK but we cannot access that memory?
int x = 551;
int* p = &x;
++p;
--p;
std::cout << *p << '\n';
Because I've already read that we should not increment/decrement a pointer that doesn't point to an element in a sequence or an array for example.
So can someone explain what will happen and whether my example is OK (de-referencing pointer p)? Thank you!
When a pointer is incremented, it actually increments by the number equal to the size of the data type for which it is a pointer. For Example: If an integer pointer that stores address 1000 is incremented, then it will increment by 2(size of an int) and the new address it will points to 1002.
Try using (*count)++ . *count++ might be incrementing the pointer to next position and then using indirection (which is unintentional).
Pointer arithmetic and arrays. Add an integer to a pointer or subtract an integer from a pointer. The effect of p+n where p is a pointer and n is an integer is to compute the address equal to p plus n times the size of whatever p points to (this is why int * pointers and char * pointers aren't the same).
when pointer arithmetic applies to a pointer that points to an object, the pointer is considered to point to an array of that object type with only one element, as said in the standard.
An object that is not an array element is considered to belong to a single-element array for this purpose
In you example, the pointer p
as if it point to int arr[1] = {551}
So, the corresponding operation is similar to apply to a pointer that point to the arr
. That means, ++p
will make p
point to the element arr[1] (hypothetical), and --p
will make p
point to the first element arr[0] again. So, in the last, de-referenceing pointer p
is OK and does not result in any UB.
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