1

according to the definition

char *str = "ankit"

here str is a pointer to char.

when we do something like

cout<< str;

then it is printing ankit. why not the address where ankit is stored, as str is a pointer so it must be a address

I have tried to print *str which comes out to be "a"; which I can understand but I am unable to understand why printing str is not giving pointer but the string value.

char * str = "ankit";
cout<< str;

output : ankit

user4581301
  • 33,082
  • 7
  • 33
  • 54
Ann
  • 53
  • 8
  • See what happens if you do `cout << reinterpret_cast(str);`. Also see [Why does my pointer output a string and not a memory address in C++?](https://stackoverflow.com/q/7788639/608639) and [cout << with char* argument prints string, not pointer value](https://stackoverflow.com/q/17813423/608639). – jww Jul 13 '19 at 05:44
  • Smurf. I should have realized this was answered and answered again. – user4581301 Jul 13 '19 at 05:48
  • 1
    Interesting side note: `char * str = "ankit";` is illegal according to the C++11 Standard and subsequent C++ Standards. String literals are constant arrays of characters and you are not allowed to use a non-constant pointer to point at constant data in order to prevent accidents where the constant data is written to. – user4581301 Jul 13 '19 at 05:48

1 Answers1

1

ostream has different overloads for char * and T * (for a template type T).

From the <ostream> header file:

template <class _Traits>
inline basic_ostream<char, _Traits>& operator<<(basic_ostream<char, _Traits>& _Ostr,
    const char* _Val) { // insert NTBS into char stream
template <class _Ostr, class _Ty,
    enable_if_t<conjunction_v< // prevent infinite recursion
                    negation<is_lvalue_reference<_Ostr>>, is_base_of<ios_base, _Ostr>, _Can_stream_out<_Ostr, _Ty>>,
        int> = 0>
inline _Ostr&& operator<<(_Ostr&& _Os, const _Ty& _Val) { // insert to rvalue stream

The function accepting char * parameters would be used if a known C string is given.

If it is not available, the other function that accepts arbitrary pointer values would be used.

There is also a method that accepts a void * pointer.

user4581301
  • 33,082
  • 7
  • 33
  • 54
SOFe
  • 7,867
  • 4
  • 33
  • 61