So I've read somewhere that in case we have a pointer p, and some values i and j defined one after another, then those values on stack will be one after another however that for me at least does not seem to be the case.
int i = 10;
int j = 20;
int *p = &i;
p++;
(*p) = 30;
std::cout << i << " " << j << " " << (*p) << "\n" ;
Instead it will print these values 10 20 30
If I commented the (*p) = 30;
instead inside *p
will be an empty address.
I thought that the ++ operator in this case will change my reference from i
to j
and the (*p)
will change the value of j
, but that isn't the case apparently .
So I was wondering what did they mean ?
A pointer in c is an address, which is a numeric value. Therefore, you can perform arithmetic operations on a pointer just as you can on a numeric value. There are four arithmetic operators that can be used on pointers: ++, --, +, and -
*p2 = *p1 means that p2 is now pointing to whatever value p1 is pointing to. Yet, p2 = p1 means that p1's value is now copied into p2.
Pointers are arguably the most difficult feature of C to understand. But, they are one of the features which make C an excellent language. In this article, we will go from the very basics of pointers to their usage with arrays, functions, and structure.
The behaviour of your code is undefined.
Pointer arithmetic is only valid within arrays. You can't access an object by increasing a pointer to another object and dereferencing that pointer. In a little more detail, p++
is defined (an object can be considered as a single element array and you are allowed to set a pointer to one past the end of an array), but the subsequent dereference is undefined.
I thought that the ++ operator in this case will change my reference from i to j and t....
That is wrong. For this definitions:
int i = 10;
int j = 20;
There is no rule that would make j
be stored in a memory location adjacent to i
.
Moreover, don't confuse pointers (the abstract concept) with what they model (the physical memory address). For most things it is fine to think of pointers as addresses in physical memory, however, strictly speaking they are not.
The C++ standard defines certain rules for pointers and what you can do with them. Incrementing a pointer to an int
to get the pointer to another int
defined right after is not one of those rules! Note that even if in your hardwares memory the two integers will be stored in adjacent memory then still incrementing a pointer to i
and then dereferencing it is undefined behaviour.
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