0

I can't understand why cout prints DATA for str variable. str does not contain the memory address of the first caracter ? What does it mean DATA ?

#include<bits/stdc++.h>

using namespace std;

int main()

{

    char str[7]=”DATA”;

    cout << str[2]<<” “<<str;

    return 0;

}

It prints T DATA.

Thank you for your help,

Zoya
  • 1,195
  • 2
  • 12
  • 14
  • `operator<<` have overload for `const char*` which display as string, and not as pointer. – Jarod42 Jan 14 '23 at 14:56
  • what do you think that bits header does? why that using statement? what are those quote marks? why no newline on your output statement? – Neil Butterworth Jan 14 '23 at 14:58
  • See [Why should I not #include ?](https://stackoverflow.com/q/31816095) and [Why using namespace std is bad practice](https://stackoverflow.com/questions/1452721). – prapin Jan 14 '23 at 15:02

2 Answers2

2

operator<< has an overload for const char* that prints out characters until it hits a null terminating character. And a char[] array decays into a char* pointer to its 1st element.

So, when we print str[2] it just prints the single character T, but when we print str it prints all of the characters.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
0

str[2] is a single char, T, which you see.

str, on the other hand, is a char* (read: pointer to char), and cout will print it as a c-string - i.e., print all the characters until it reaches the null character (\0), similar to what printf would have done. If you don't want that overload, you could cast it to a void*:

cout << str[2] << " " << (void* ) str;
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • "*`str` ... is a `char*`*" - technically, `str` is a `char[]` array that *decays* into a `char*` pointer in certain contexts, such as when passed by value in a function parameter. – Remy Lebeau Jan 14 '23 at 17:36