0

I am learning C++ and I was recently learning about references and pointers when I stumbled upon this problem. I have a file called logging.cpp and it defines a logging function, which takes in a const char* msg parameter. The function body looks like this:

void Log(const char* msg) {
    std::cout << msg << std::endl;
}

iostream is included, I just didnt include it here.

When I use this function in my main file like this:

...
Log("Hello");
...

It prints the whole message. But don't pointers point to a memory address? When I ran this, I expected it to print a memory address. Actually, when I try to dereference it, it only gives me the first letter of the argument ("H").

Why does this happen? I used to think pointers should be dereference in order for the thing they are pointing to to be used.

Squiggles
  • 21
  • 4
  • 3
    There is a specific overload of `operator<<()` for `std::ostream` and `const char*` - to make output of C strings convenient. (It's number (2) in [operator<<(std::ostream)](https://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt2).) – Scheff's Cat Mar 24 '23 at 11:34
  • 1
    To print memory addresses, you have to convert the `const char*` to `const void*`. It's number (8) in [std::ostream::operator<<](https://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt). – Scheff's Cat Mar 24 '23 at 11:38
  • 1
    And, please note: Dereferencing a `const char*` results in `const char` - a single character. There is as well (of course) an overloaded stream `operator<<` for `char` and it prints (surprise) one character... ;-) – Scheff's Cat Mar 24 '23 at 11:40
  • @Scheff'sCat Thank You, now I understand it. I was following The Cherno's c++ videos, ad at least how far I had been, it didn't mention this case. – Squiggles Mar 26 '23 at 13:46

0 Answers0