1
#include <iostream>
using namespace std;

int main() {
    char a[][6] = { "hello", "hii" };
    cout << a << ", " << *a << ", " << **a;
    return 0;
}

OUTPUT : 0x7ffd1f44a20c, hello, h

Now, as we know that the array-name(in this case 'a') in case of 2D array points to the 1D array (in this case "hello"), *a will point to the element in that (1D array pointed by a) array and **a will give use the value pointed by *a. Now in this case i am little confused because of two reasoning:

  1. The output is right, since the value pointed by 'a' is "hello", and *a will print the value pointed by 'a'.
  2. The output is wrong, since *a itself is pointing the element inside 1D array and hence *a should have printed the address corresponding to the first element of 1D array pointed by a and the output should have been :

Expected output : 0x7ffd1f44a20c, address of h, h

Thank you very much for patience!

yash
  • 77
  • 3
  • 10
  • 4
    cout operates differently when passed a char* Related: [https://stackoverflow.com/questions/29188668/cout-and-char-address](https://stackoverflow.com/questions/29188668/cout-and-char-address) – drescherjm Jun 06 '22 at 17:24
  • please don't put images in future posts - just write everything in text ... – OrenIshShalom Jun 06 '22 at 17:51
  • @ OrenIshShalom, just wanted to make sure that people understand my doubt! – yash Jun 06 '22 at 17:54

1 Answers1

2

a is only a "2D array" in a limited sense. This is part of the somewhat-weird and not-super-consistent array semantics C++ inherits from C, like array-to-pointer decay.

So, when you define a, what gets placed in memory is: h, e, l, l, o, \0, h, i, i, \0, \0, \0 - in sequence.

  • When you type a[x][y], that's the x*6 + y'th character in that sequence (type char);
  • When you type a[x], that decays into a char* pointing to the x*6'th character in the sequence.
  • When you type a, that decays into a pointer to 6-element arrays, pointing to a 6-element array starting at the 0'th position in the sequence.

See this also on GodBolt (using the type_name facility).

einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • then like what is datatype of `a`, i am actually confused that what is `a`? – yash Jun 06 '22 at 17:49
  • @trev : See the link. The confusing thing is that there's a "decay" from the datatype into something else, so that if you pass it, say, to a function - it gets the "decayed" type; but for template instantiation purposes, the non-decayed type is used. – einpoklum Jun 06 '22 at 17:50
  • @ einpoklum, actually i am fairly beginner in programming, can you explain "decay" in simple language so that i can build concept on top of it? – yash Jun 06 '22 at 18:01
  • @trev: Follow the link I gave about array decay, that's a question explanation. You might also want the C language FAQ about arrays, [here](http://c-faq.com/aryptr/index.html). – einpoklum Jun 06 '22 at 18:11