0

For the code given below, why is the output "This is the string" instead of the address of the first character in the string, 'T'?

int main()
{
    char myString[] = "This is a string";
    char *ptr = &myString[0];
    cout << ptr << endl;
    return 0;
}

enter image description here

Output is to be clicked above.

MD XF
  • 7,860
  • 7
  • 40
  • 71
Trung Vo
  • 1
  • 2

2 Answers2

1

why is the output "This is the string" instead of the address of the first character in the string, 'T'?

There is an operato<< overload whose LHS is a std::ostream and the RHS is char const*. This function prints the string.

If you want to print the address of 'T', you can cast the pointer to a void*.

cout << static_cast<void*>(ptr) << endl;
R Sahu
  • 204,454
  • 14
  • 159
  • 270
0
char *ptr = &myString[0];

Means make ptr point to the first character of myString. Thencout has an overload of << that takes a char * and will print what it points to and and the preceding elements until it reaches an '\0'

If you want to print the address of the array then you need to convert the pointer to something else like a void* first and then print:

cout << reinterpret_cast<void*>(ptr) << endl;
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • _....char * and will print what it points to and and the preceding elements until it reaches an '\0'_. Did you mean _following elements_ instead of _preceding elements_? – a_sid Sep 19 '20 at 20:09