c++pointers

Accessing memory byte by byte


I have been learning about pointers in C/C++ since quite few days and wanted to execute the following code.

#include <iostream>
using namespace std;
int main(){

    int x = 1025;
    int *p = &x;
    char* myp = (char*) p;
    cout << *myp << endl;
    return 0;
}

This code compiles and runs perfectly except that the output is some weird character (in VS code) and blank in terminal.

As far as I understand pointers, they store address of a particular variable. We specify the data type of the pointer so that it reads that many bytes from that particular memory address. So 1025 should have been stored as 00000000 00000000 00000100 00000001 with the address of 00000001 stored in pointer p. When I typecast the pointer to a character pointer then on dereferencing the program should read only one byte from the memory location. For this reason, I expected an output of 1.

This program runs perfectly in C, however gives wrong output in C++. What is the fallacy in this logic/code?


Solution

  • The overloaded << operator for cout is receiving a char as its argument, and as a result it is printing the character associated with the value.

    So for example, assuming ASCII, if the value given was 65 it would print A.

    You need to cast the value to type int so the proper overload is applied:

    cout << static_cast<int>(*myp) << endl;