Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `(void *)&` get the address of the variable?

Could someone explain the logic behind this? Why void? For example

#include <iostream>
using namespace std;
int main()
{
    char c;
    cout << (void *)&c;
    return 0;
}
like image 843
anon Avatar asked Dec 13 '22 07:12

anon


1 Answers

cout << (void *)&c;

takes the address of c, then casts it to void*, then prints pointer.

The intent here is to print the address of variable c. But when passing a char * to std::cout << it will attempt to print a null-terminated string. To avoid this (and print the actual address) you have to cast to void* first.


More explanation:

std::ostream::operator<< has overload (2) that handles char * and const char*. It assumes that a const char* will point to some string that is eventually terminated by a null-character '\0'. That's simply a convention used in C and C++.

You want to avoid this and instead use overload (7) to print the address.

like image 197
churill Avatar answered Dec 29 '22 12:12

churill