Reputation: 501
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 ?
Upvotes: 5
Views: 262
Reputation: 123450
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.
Upvotes: 4
Reputation: 234875
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.
Upvotes: 11
Reputation: 77
If you want to have contiguous memory locations, you would need to declare an array. Since your datatype is small, libc allocates the locations. Pointers occupy spaces around declared variables.
Upvotes: 2
Reputation: 914
The ++
operator will point to the next location in the memory not the next variable.
If you would have int i[2] = {10, 20};
then p++
will point to the i[1]
i.e. 20
Upvotes: 2