Pointer to char versus pointer to arrays

I thought I had a decent knowledge of pointers until I decided to consider some of the so-called trivial examples.

One thing I know is that when declaring an array they say:

int arr[2] {3, 5};

arrwill hold the value of the first element in the array, so trying to print it ( cout << arr) gives, obviously, an address arr[0]. Even if my program uses pointers, it is still similar.

My question is why I can print hand have bonjouras output, but I can not do the same with p?

It also looks when I enlarge h++and print it again. I get it onjour. How do different pointers differ from char?

#include <iostream>
#include <string>

int main()
{
    char* h = "bonjour";
    int k[4]{3, 4, 5, 6};
    int * p = k;

    std::cout << "Hello, "<< h << "!\n";
}
+4
4

h, :

template< class Traits >
basic_ostream<char,Traits>& operator<<( basic_ostream<char,Traits>& os,  
                                        const char* s );

p, :

basic_ostream& operator<<( const void* value );

, \0, . - const char*, .

+9

h bonjour , p? , h++ , onjour. char?

operator<< .

-:

basic_ostream& operator<<( const void* value );

, :

template< class Traits >
basic_ostream<char,Traits>& operator<<( basic_ostream<char,Traits>& os,  
                                        const char* s );

, cout << ptr , char* char const*. , tpe char* char const*. , .

.

, -.

, char* char const*. ('\0') , . . , a int* , a char*.

+2

char* , C . a char* , aka C-string. , h, p, , , char*:

 std::ostream::operator<<(std::ostream& os, const char*);

:

std::ostream& operator<<(std::ostream& os, const int* arr) {
   while (int i = *arr++) {
      os << i;
      if (*arr) os << ", ";
   }
   return os;
}

int main()
{
  const int arr[] = {1, 2 ,3, 4, 0};
  std::cout << arr << "\n";
}

However, this is extremely dangerous because most integer arrays do not end with zero, and not all pointers to integer arrays are arrays.

+1
source

I think this is more related to operator <<for char*and int*. C programmers are used to print zero lines, so a method was created to print them. intcan be printed directly. A charcannot print the whole line.

0
source

Source: https://habr.com/ru/post/1613404/