1

I was learning about pointer in cpp and I write this code but when I run this code the outcome was different from what I expected but why ?

#include <iostream>

using namespace std;

int main()
{
    char chars[] = {'a','b','g','j','z'};
    char *ptr1 = chars;
    cout << ptr1 << endl;
    
    int arr[] = {1,2,3,4,5};
    int *ptr2 = arr;
    cout << ptr2;

    return 0;
}

the output of this code is :

abgjz
0x7ffd836e4360

why the first pointer printed the whole character array but the second pointer printed the address only ?

I want to print the address of both arrays.

  • Character pointers are treated differently and assumed to point to nul terminated strings. Cast the pointer to `void*` if you want different behavior. – Retired Ninja Apr 01 '23 at 18:11

3 Answers3

1
std::cout << "hello world\n";

in the above line of code, the type of "hello world\n" is a const array of 13 char with the values {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '\n', '\0'}.

Unless you do some extra work, arrays like this decay into pointers to the first element. So this:

auto str = "hello world\n";

str has type char const*, and it points at the h.

By convention from C, pointers to characters are often treated as pointers to nul (not NULL) terminated buffers and represent strings.

Using char const*s this way is normal convention in C, and in fact a char const* that didn't refer to a nul terminated string would be unusual if it wasn't wrapped in a typedef to obscure it.

So std::ostream was taught to consume these char const*s as nul terminated strings, and print each one until it finds a '\0' character (whose bit value is all 0s).

For other pointers, it instead prints their address.

There is no easy way to distinguish between a char const* that is a pointer to a nul terminated buffer and one that is not, so they picked the more common one.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
0

They were written that way mostly because people thought (mostly correctly, I'd guess) that it would be useful that way.

As for wanting to print the address, you generally want to cast to void * first. That should be fairly reliable for printing out the address (and, in fact, it's undoubtedly how your pointer to int is being printed out now, simply because it's the only overload available that can take an argument of type int *).

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
0

The implementation of operator<< with char* operands assumes that the operand points to a nil-terminated C string and prints the C string. For other pointer type operands it makes no assumptions and prints just the pointer itself. That’s how it is defined. Can’t change it. If you want to print the pointer value, cast it to void*.

gnasher729
  • 51,477
  • 5
  • 75
  • 98