Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is incrementing/decrementing or adding an integer value to a pointer that is not pointing to an element in a sequence Undefined Behavior?

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!

like image 216
Itachi Uchiwa Avatar asked Dec 06 '20 19:12

Itachi Uchiwa


People also ask

What does incrementing a pointer mean?

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.

How do you increment a pointer to an integer?

Try using (*count)++ . *count++ might be incrementing the pointer to next position and then using indirection (which is unintentional).

What happens when an integer is added to a pointer?

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).


1 Answers

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.

like image 193
告白气球 Avatar answered Oct 23 '22 20:10

告白气球