-1

I am learning c++ and encountered this:

#include<iostream>
using namespace std;
int main(){

const char *a[] = {"ge","hy"};
cout<<a<<" "<<&a[1]<<endl;
cout<<a[0]<<" "<<a[1];
return 0;
}

The output is :

0x7fff54e71830 0x7fff54e71838
ge hy

I tried to understand the code.

Here is my understanding:

a is an array of character pointers which means that each element of the array is a char pointer.

Now, since every element is a pointer then it should store the address of "ge" and "hy" respectively.

         -----------------------------------
 a  =    | 0x7fff54e71830 | 0x7fff54e71838 |
         -----------------------------------

Now when I write a[0] and a[1] then why does it print the ge hy and not the memory address of them because the array a stores their address and not their actual value.

I am sure that I'm going wrong somewhere because the output is not as expected. Kindly, correct me here.

Ajay Negi
  • 71
  • 11
  • "Ignoring the warnings". Nope, go back there and see what's happening..Hold your horses Rahul.. Understand that, and then proceed.. – gsamaras Jan 12 '19 at 21:27
  • Maybe [this](https://stackoverflow.com/questions/17813423/cout-with-char-argument-prints-string-not-pointer-value/17813845) can help – dWinder Jan 12 '19 at 21:28
  • @gsamaras I read it somewhere that `"abc"` is `const char a[]`. Isn't it right? – Ajay Negi Jan 12 '19 at 21:32

1 Answers1

3

The standard library provides an overloaded operator<<(std::ostream&, const char*) for printing C-style strings that prints the string pointed to rather than the value of the pointer itself. That overload is a better match than the operator<<(std::ostream&, void*) overload that prints the address stored in a pointer.

If you want to print the value of the pointer, add a cast to void*:

std::cout << static_cast<void*>(a[0]) << ' ' << static_cast<void*>(a[1]) << '\n';

Live Demo

Miles Budnek
  • 28,216
  • 2
  • 35
  • 52
  • Is this also the case with `char*`? Can I know how the `operator<<` is overloaded for different types in c++ without searching on Internet? – Ajay Negi Jan 13 '19 at 05:30
  • Also, for char c[] = {'a','b','c'}; then std::cout << c << '\n'; also prints abcand not the address of array `c`. Why is this printing abc and not the pointer value? – Ajay Negi Jan 13 '19 at 06:01
  • The `const char*` overload is a better match than the `void*` overload for `char*` since it only requires a const-conversion, as opposed to a type conversion. Similarly, it's a better match for `char[N]` since it requires only one type conversion and one const-conversion (`char[N]` -> `char*` -> `const char*`) while a conversion to `void*` requires two type conversions (`char[N]` -> `char*` -> `void*`) – Miles Budnek Jan 13 '19 at 06:31