YuanLinTech
YuanLinTech

Reputation: 83

Increment an integer pointer and assign the value of the incremented pointer to another variable in C++

I wrote the following code in Microsoft Visual Studio:

#include <iostream>
using namespace std;

int main()
{
    int i = 1;
    int *p;
    int val;
    p = &i; 
    *p = 101; 
    val = *(p + 2);
    cout << val << endl; 
    cout << i << endl; 
    return 0;
}

In the line val = *(p + 2), since *(p + 2) returns the value of the second integer after the one to which p points, and p currently points to the integer 101, I expected val to be of value 101+4×2=109.

When I executed the code in Visual Studio, the output showed the value of variable val was instead a random garbage value. Why was this so?

Upvotes: 0

Views: 279

Answers (3)

user31264
user31264

Reputation: 6737

You got it all wrong.

p points to i. It means that p stores the address of i. Which adress it is, is unpredictable. It may be 123456. We only know that at this adress, the number 101 is written.

*(p+2) is the integer which is stored in memory at 2 positions after i. For instance, if i has address 123456, and integer is 4 bytes, then (p+2) is an integer at address 123464 (which is 123456+24). What is stored here, and why, is unpredictable.

Just like if you live at Flying Macaron Monster Rd. 12345, I have no idea who lives at Flying Macaron Monster Rd. 12346 or Flying Macaron Monster Rd. 12347.

Upvotes: 1

user13526133
user13526133

Reputation:

val = *(p + 2); does not points to value of some second integer after i=101. p pointer has its own memory address in the memory and when you write p + 2 you went ahead two memory address, equal to the size of your pointer size in memory times 2. So val gets value at (p+2) address, which is garbage. Check out cout << &p and cout << &(p+2). They are different and one points to i and other holds garbage value.

Upvotes: 0

eerorika
eerorika

Reputation: 238421

p currently points to the integer 101, I expected val to be of value 101+4×2=109.

Your expectation is ill-founded.

since *(p + 2) returns the value of the second integer after the one to which p points

This would be correct if p pointed to an element of an array. But it doesn't point to an element of an array, and because it doesn't point to an element of an array, it also follows that there is no "second integer after the one which p points".

Why was this so?

Because the behaviour of the program is undefined.

Upvotes: 3

Related Questions