简体   繁体   中英

Initialize 2D Array with characters c++

I am trying to initialize a 2D array to create a map that will print out stars at the beginning of the program. I have my initialization in a function. Whenever I try to run the program, I get crazy numbers. Any tips on how to make this 2D array correct? This is my code and the result that I get:

void InitializeArray()
{
char map[Y_DIM][X_DIM];

for (int row = 0; row < Y_DIM; row++)
{
   for (int col = 0; col < X_DIM; col++)
   {
      cout << map[row][col];
      cout << "*";
   }
cout << endl;
}
}

This is my result

`*2*.*v*/***************
******************
?*?*?*u*/****?*?*?*?*?*?*?*?*?*!*`**
****?*!*`******?*!*`******
?*-*?**?****U*?*7*v*/****?**@**
****?*?*7*v*/*****E*]*v*/****
?*!*`*******-*?**?****?*!*`**
****?**@******p*    *@******
?*-*?**?****************
****?*?*7*v*/****p* *@******

That is not initializing the array, it's printing it. Given that it's not initialized, it prints garbage.

Instead of:

 cout << map[row][col];

you want:

map[row][col] = '*';

That will set the initial value for each cell in your array, which is to say, initialize it.

You can also do this at the same time you define the array using C++'s array initializer syntax, but your approach is better.

What I'd do:

#include <iostream>
using namespace std;
const int Y_DIM = 8;
const int X_DIM = 9;
void initializeArray() {
    char map[Y_DIM][X_DIM]={'*'};
    for (int row = 0; row < Y_DIM; row++)
    {
        for (int col = 0; col < X_DIM; col++)
        {
            map[row][col]='*';
            cout << map[row][col];
        }
    cout << "\n";   
}
}
int main() {
    initializeArray();
    return 0;
}

Output

*********
*********
*********
*********
*********
*********
*********
*********

Try it on ideone.com

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM