0

I have the following problem:

int a[2][2]={{1,2},{3,4}};
cout<<a[1]; //the output is 0x29ff18 , which is an address
--------------------------------------------------------------------
char b[][6]={"hello","there","now"};
cout<<b[1]; //the output is there, which is value of b[1]

I am wondering why b[1] will not give an address like a[1]...

thanks!

jackycflau
  • 1,101
  • 1
  • 13
  • 33
  • `a[1]` and `b[1]` are arrays, not addressess. But that's not related to your apparent issue. – Mooing Duck Oct 16 '15 at 22:21
  • I don't know why the outcome would be different – jackycflau Oct 16 '15 at 22:24
  • The expression `b[1]` is implicitly converted to `char*`, the stream overload for `char*` prints a string, if you want the address you'll need to cast: `std::cout << static_cast(b[1]);`. It prints the address in the case of `a` because there's no better overload for `int*`. – user657267 Oct 16 '15 at 22:35

2 Answers2

2

The basic difference between in a character array and an integer array is the terminating null character : \0 If you declare your character array like this : char b[] = {'h','i'}; Then your cout statement fails to identify what to do, and will give strange output. But as soon as you do :

char b[] = {'h','i','\0'};

or

char b[] = "hi";

Your cout works fine. This is because in first, you are explicitly adding a null character at the end, and in the second, it gets added automatically by the compiler.

And for the array, and array declared as a[] or a[][], the compiler stores the address of the first element of the array in variable a, so you get the address of the first element in case of an non-character array. Refer to this link for more info : What is the difference between int and char arrays?

Community
  • 1
  • 1
Sahil Arora
  • 875
  • 2
  • 8
  • 27
-1

The type of v determines what cout << v prints.

One case you have int array, other case you have char array. Cout by definition prints a char array different than int array. Just the way it is. As bjorne.

steviekm3
  • 905
  • 1
  • 8
  • 19