0

I'm a bit stumped that passing an array of char values to a const char* prints the entire string literal.

void log(const char* message)
{
    std::cout << message << '\n';
}

When I dereference 'message' in cout, it prints the first element of the char array passed, which is what I expected; however, the fact that 'message' is a pointer to the whole string literal rather than the first element is confusing me. Why aren't I just getting an address to the first element like I would if I used an int instead of char? Is it something to do with a char being just 1 byte?

Njgardner90
  • 61
  • 1
  • 7
  • 2
    There's an overload of `<<` specifically for `char *` and `const char *` that prints it as a C-style string. – Barmar Jan 11 '21 at 21:56
  • Thanks, that makes sense :) – Njgardner90 Jan 11 '21 at 21:59
  • When an array is passed as an argument, the function receives a pointer to the first element of that array. A string literal is represented as a nul terminated array of static storage duration. In the call `log("A")`, the literal `"A"` is an array of two `char` (`'A'` and `'\0'`). Your function `log()` receives the address of the first `char` in that array (which has value `'A'`). Standard output streams, like `std::cout`, have an `operator<<()` that accepts a `const char *`, ASSUMES it is the address of the first `char` in an array, and prints each `char` until the terminating `'\0'`. – Peter Jan 11 '21 at 22:04

0 Answers0