0

So i was learning about pointers. I tried to experiment myself with pointers so that i could get to know more about it. Here's the code :-

#include<iostream>
using namespace std;

int main() {
    char *names[] = {
            "james","krushi","kush","assh","kitu","kudi"
    };

    char **total[4];
    total[0] = &names[0];
    total[1] = &names[1];
    cout<<endl<<"names[0] = "<<names[0]<<endl;
    cout<<endl<<"&names[0] = "<<&names[0]<<endl;
    cout<<endl<<"names[1] = "<<names[1]<<endl;
    cout<<endl<<"&names[1] = "<<&names[1]<<endl;
    cout<<endl<<"names[2][0] = "<<names[2][0]<<endl;
    cout<<endl<<"&names[2][0] = "<<&names[2][0]<<endl;
    return 0;
}

and the output of the last two lines are really unexpected. Like how could it print the whole string instead of the memory address?

Output :-

names[0] = james

&names[0] = 0x7ffc79776e30

names[1] = krushi

&names[1] = 0x7ffc79776e38

names[2][0] = k

&names[2][0] = kush
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
  • Please don't spam language tags. C and C++ are different languages, and both tags rarely apply for the same question. – cigien Dec 27 '20 at 17:55
  • Let's say that `char*` is a special type of pointer for C++. It usually points to a zero-terminated string and most standard library routines treat it like that. – Aykhan Hagverdili Dec 27 '20 at 17:57
  • In the last `cout`, one `&` and one `[]` cancel each other out. You're left with a `char*` for which `<<` does something special (read the duplicate target for details). – cigien Dec 27 '20 at 17:58
  • 1
    Because `char*` is commonly used to hold a string (you do it yourself). So `cout` has an overload to conveniently print out strings, that overload is invoked when the argument is `char*`. If you want to see the address then cast the argument to `void*`. – john Dec 27 '20 at 17:58

0 Answers0