kuhi
kuhi

Reputation: 697

Wrong values after first cout

I'm making a test program for starting with C++ :)

It's showing wrong values after first print

enter image description here

This is the code (very simple)

#include "pch.h"
#include <iostream>
#include <Windows.h>
using namespace std;

int main()
{
    int varInt = 123456;
    char varString[] = "DefaultString";
    char arrChar[128] = "Long char array right there ->";
    int * ptr2int;
    ptr2int = &varInt;
    int ** ptr2ptr;
    ptr2ptr = &ptr2int;
    int *** ptr2ptr2;
    ptr2ptr2 = &ptr2ptr;

    while(1){
        cout << "Process ID: " << GetCurrentProcessId() << endl;

        cout << "varInt (0x" << &varInt << ") = " << varInt << endl;
        cout << "varString (0x" << &varString << ") = " << varString << endl;
        cout << "varChar (0x" << &arrChar << ") = " << arrChar << endl;

        cout << "ptr2int (0x" << hex << &ptr2int << ") = " << ptr2int << endl;
        cout << "ptr2ptr (0x" << hex << &ptr2ptr << ") = " << ptr2ptr << endl;
        cout << "ptr2ptr2 (0x" << hex << &ptr2ptr2 << ") = " << ptr2ptr2 << endl;

        cout << "Press ENTER to print again." << endl;
        getchar();
        cout << "-----------------------------------" << endl;
    }

    return 0;
}

The expected results are obvious, as the code is published as is:

Upvotes: 0

Views: 138

Answers (1)

Peter Cheng
Peter Cheng

Reputation: 758

1e240 is the same thing as 123456 in hex. The first iteration will print 123456 correctly but after you set the base flag of cout to hex mode, you need to set it back to dec to print 123456 again on the next loop.

cout << "varInt (0x" << &varInt << ") = " << dec << varInt << endl;

See here for documentation.

Upvotes: 3

Related Questions