Multidimensinal arrays

0 Syntax3rror Code · September 26, 2014
Can someone tell me why this

void printBoard();

    const int a = 3;
   int test[a][a] = {{0,0,0},{0,0,0}};
int main()
{
printBoard();

    return 0;
}
void printBoard(){
  for(int i = 0; i < a; i++){
        for(int x = 0; x < a; x++){
            cout << test[x];
        }
        cout << endl;
   }
}

will output: 000
                  000
                  000
But this

void printBoard();

    const int a = 3;
   char test[a][a] = {{'x','x','x'},{'x','x','x'}};
int main()
{
printBoard();


    return 0;
}
void printBoard(){
  for(int i = 0; i < a; i++){
        for(int x = 0; x < a; x++){
            cout << test[x];
        }
        cout << endl;
   }
}

outputs : xxx
               xxx

I know the first one is int the second one is char but i just dont understand why the second one doesnt print   xxx
                                                                                                                                                                               xxx
                                                                                                                                                                               xxx
and how do i print xxx
                             xxx
                             xxx


Post a Reply

Replies

Oldest  Newest  Rating
0 Franz Schmidt · September 26, 2014
I don't even know how you get
000
000
000 
with just test[x].
If I compile your code I get this:
/images/forum/upload/2014-09-26/06f40bb0c293fdea938580f5ca3953ee.PNG

If you want to print every element of the matrix you need to use the output like a matrix:
void printBoard(){
for (int n = 0; n < a; n++){
for (int x = 0; x < a; x++){
cout << test[n][x];
}
cout << endl;
}
}

/images/forum/upload/2014-09-26/c3c1336809974764dd50fa422331906a.PNG



Than also the other code with the char array will work (but just with two lines!)

I hope you intended not to fill your complete array...
The reason why the int output has 3 lines is, that if you don't declair a part of your array it gets automatical filled with 0 (just integer).
But if you have a char array the array doesn't get filled with a value (or just filled with '\0') and you can't print those lines


EDIT: Sorry didn't recognized buckysroom has a bug and doesn't show  :ermm:
  • 1

C++

106,942 followers
About

Used in many types of software including music players, video games, and many large scale applications.

Links
Moderators
Bucky Roberts Administrator