0

I read from the website that *ch[] is in actual 2D array or characters but when I myself wrote 2D array in C++ results were different. Can anyone describe why it is so?

Here is my code:

#include <iostream>
using namespace std;
int main()
{
    char ch[3][2] = {{'1','2'},{'3','4'},{'5','6'}};
    cout<<ch[0]<<endl;
    char *cha[3] = {"12","34","56"};
    cout<<cha[0];
    return 0;
}

and it is returning:

123456
12
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
saqib
  • 11
  • 2
  • where did you read that? `char * char[3]` is an array of pointers – 463035818_is_not_an_ai Jun 29 '20 at 11:54
  • Also, note that your second array (`cha[3]`) is an array of pointers to string literals, each of which consists of ***three*** characters (the two digits plus the `nul`-terminator). If you make your first array into: `char ch[3][3] = {{'1','2',0},{'3','4',0},{'5','6',0}};` (note there are no quotes around the zeros) then you will see similar output. – Adrian Mole Jun 29 '20 at 11:57

2 Answers2

5

They are not the same thing. char[] will decay to a char*, so for cout << ch[0], the function that's used is std::ostream &operator<<( std::ostream &out, const char *str ). Since your ch[][] array doesn't have any null terminators, it keeps printing until it finds one (what you actually have, in UB). Yours just so happens to end after '123456', but there's nothing guaranteeing that.

char *cha[3], however, constains three char *s, and are assigned three c-strings, which are null terminated. So, it prints, as you would expect, '12'

ChrisMM
  • 8,448
  • 13
  • 29
  • 48
2

Are char ch[][] and char *ch[] both are same

No, they are not the same.

char ch[][] is an array of indeterminate length of arrays of indeterminate length. Such array is ill-formed because array element may not be an array of indeterminate length.

char *ch[] is an array of indeterminate length of pointers.


char ch[3][2] = {{'1','2'},{'3','4'},{'5','6'}};
cout<<ch[0]<<endl;

Here, you insert a pointer to a character (the array implicitly converts to pointer to first element) into a character stream. The character stream requires that such character array (i.e. string) must be null terminated. Your character array is not null terminated. As a consequence of violating the pre-condition, the behaviour of the program is undefined.


char *cha[3] = {"12","34","56"};

This on the other hand is ill-formed in C++11 and later, because you are initialising pointers to non-const with a const array (the string literal). To fix this, use an array of pointers to conts char instead.

eerorika
  • 232,697
  • 12
  • 197
  • 326