Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I convert a pointer address (i.e. an hex integer) to decimal and octal base int in C++

Tags:

c++

pointers

#include <iostream>

using namespace std;

int main()
{
    int *a = nullptr;
    int b;
    a = &b;

    cout << noshowbase;
    cin >> b;
    cout << dec << a << '\t' << oct << a << '\t' << hex << a;
}

Consider this code.. It is designed to convert a variable's (here b) address (&b or a) which is a hex integer to dec and oct values using <iostream> stream manipulators.. But on running, the output is same for all of them(hex,dec,oct).. Neither, there is any compilation error. So can you please elaborate the reason for this?? Also the noshowbase does not seems to be having any effect on output.. 0x is output anyways before the address..

like image 428
anshabhi Avatar asked Feb 10 '23 06:02

anshabhi


1 Answers

An address is not a hex integer. It's an address.

It just so happens that an address is implemented as an integer, referring to a memory location, and can be reinterpreted as an integer. This is rarely a useful thing to do (particularly if you are a fan of bug-free code), but it comes up now and again. You can use reinterpret_cast<uintptr_t>(a) to do that. (Note that converting to int will not, in general, work properly. Remember what I said about bug-free code.) When you print the resultant integer, it will print as a decimal, octal, or hexadecimal integer, depending on the currently-set base.

like image 146
Sneftel Avatar answered May 16 '23 03:05

Sneftel