Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unexpected output C++

I started learning Cpp after Python, so some results are not really obvious for me.

I have this code:

#include <iostream>

using namespace std;

int main()
{
    int a = 10;
    int *b = &a;
    b += 1;
    cout<<b;

    return 0;
}

And it returns different value every time, for example 0x7fff0dabe070.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I know this 0x means hexadecimal number, but why doesn’t it just return 11 or at least the same number every time?

>Solution :

To get the expected result you should write

int a = 10;
int *b = &a;
*b += 1;
cout<<*b;

Othewise in this statement

b += 1;

there is used the pointer ardithmetic and in this statement

cout<<b;

there is outputed the address of the memory just after the object a stored in the pointer after the pointer arithmetic

To get a value of an object pointed to by a pointer you need to dereference the pointer.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading