Search code examples
c++pointerscharvariable-address

displaying address of char variable in c++ using pointers?


how can we display the address of char variable? I have found a solution using type casting by fist converting it to int or float or void etc. and then displaying address using pointers. But is there any other alternative to particular solution without type casting? using pointers like

char var = 'a'; 
char* ptr; 
ptr = &var; 
cout << ptr;

but in this case even the pointer is pointing to the address of var but displays the value of var. why? and if its so then how do we get he address of var using pointers? without using type casting

cout << "Address of var = " << static_cast<void*>(&var)  << endl;

or we have to overload any operator for particular problem?


Solution

  • The only reason that you need to write the cast is because std::ostream has a special overload for char * which assumes that the given pointer points to the first element of a zero-terminated array of characters and will happily try to traverse that array until it hits zero.

    Unfortunately, that means that you cannot simply pass the address of a single character and have the value of that address printed, which is why you need the cast. For all other (non-character) pointers, std::ostream already prints a numeric representation of the pointer value.

    There isn't anything you can "do", but also there isn't really a problem, since you've already discovered the solution. If you are in a generic setting and want to print object pointers, then just add a cast to void * and it will work for all input types. The behaviour of std::ostream is the result of a design choice for convenience to make the vast majority of use cases work easily, at the expense of making your particular use case more verbose to write.