简体   繁体   中英

C++ Printing Array

So I have a 2d array I'm using as a gridmap where each array block is a space on a map.

So in my main() I've initialized array 'Map' with

char Map[ROWS][COLS]={'x'};

ROWS = 10 and COLS = 20

Later I call function PrintMap with

void PrintMap(const char Map[ROWS][COLS], const bool showTreasure)
{


for (int countr=0; countr<ROWS;countr++){
    for (int countc=0; countc<COLS;countc++){      //print map
            if (!showTreasure){
                    if (Map[countr][countc]!='T')
                            cout << Map[countr][countc];
                    else
                            cout << '*';
            } else {

                    cout << Map[countr][countc];

            }
    }
cout << endl;
}



}

One space on the grid is where the treasure or goal in the game is located. In the parameters for PrintMap is bool showTreasure which is whether or not you want a 'T' to be shown on the map or if you want to hide it.

So one of the spaces in the array will be a 'T' while all the others will be either '*', 'X', or 'P'.

The * is where nothing is located.

So the if statements are supposed to say: If showTreasure is false (meaning you want to hide the 'T'): you print what is in the array if it's not a 'T' or print an '*' if it is a T.

Now my problem is that even I've initialized the array with 200 *s, when I run the program it only prints out 1 *.

If your initialization is this line:

char Map[ROWS][COLS]={'x'};

Then the matrix is initialized to a single x followed by 199 NULL characters.

See the excellent explanation at https://stackoverflow.com/a/201116/29157 .

For more about std::fill() see https://stackoverflow.com/a/3948314/29157

Thanks for the tip, CantChooseUsernames !

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