NeomerArcana NeomerArcana - 2 months ago 6
C++ Question

How can I get the address of a char&?

This code compiles but doesn't generate the results I'd expect:

#include <iostream>

int main()
{
char h = 'h';
char& href = h;

std::cout << &href << std::endl;

int x = 1;
int& xref = x;

std::cout << &xref << std::endl;
}


The result is something like:

h
0x22fe38


How do I retrieve the address of the
char
my
char&
is aliasing?

Answer

How do I retrieve the address of the char my char& is aliasing?

The expression is &href.

The problem you are seeing is due to the fact that the type of &href is char*. Hence,

std::cout << &href << std::endl

tries to print a null terminated string. You can use

std::cout << (void*)&href << std::endl

to print the address.

Comments