savannaalexis
savannaalexis

Reputation: 65

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* *@******

Upvotes: 0

Views: 2485

Answers (2)

David Merinos
David Merinos

Reputation: 1295

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

Upvotes: 0

Mud
Mud

Reputation: 28991

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.

Upvotes: 3

Related Questions