0

I just started learning C++. I learned Java before and I found that C++ is very similar in terms of structure.

Here is a 2D array and I traverse it and print all the values to make a 3 by 3 grid of 0's. But it prints out weird numbers:

#include <iostream>
using namespace std;

int main() {

    int board[3][3];
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
            cout << board[i][j] << " ";
        }
        cout << "\n";
    }

}

This prints out:

0 0 0 
0 -13088 0 
-13168 0 -12816 

Edit: Thank you! I didn't know that C++ needed initialization. Arrays in Java are stored with 0's by default. Will keep this in mind while learning!

5
  • 2
    Uninitialised array contains garbage. Try this: int board [3][3]{}; Commented Jul 1, 2021 at 7:17
  • you din assigned any value to array Commented Jul 1, 2021 at 7:17
  • In c++ you have to initialize your variables, if you don't they will contain random values. Try with int board[3][3]{}; Commented Jul 1, 2021 at 7:18
  • " I found that C++ is very similar in terms of structure." -- beware of this line of thought. Java and C++ may have a similar syntax for certain constructs, but they are rather different languages. Some simple code blocks may look exactly the same in both languages, but when you start dealing with (among many others) pointers, memory management, and undefined behavior you realize that the differences are huge. Commented Jul 1, 2021 at 8:29
  • Regarding your edit: "Edit: Thank you! I didn't know that C++ needed initialization. Arrays in Java are stored with 0's by default. Will keep this in mind while learning!". - That doesn't belong in your question. You can thank people by accepting their answer (if you've gotten a helpful answer). There should be a grayed out checkbox next to the answers you get. Commented Jul 1, 2021 at 11:29

1 Answer 1

2

initialization is missing

int board[3][3] = {{1,2,3},{1,2,3},{1,2,3}};

output

1 2 3 
1 2 3 
1 2 3 
Sign up to request clarification or add additional context in comments.

3 Comments

True, but please note that the OP want "to make a 3 by 3 grid of 0's".
int board[3][3] = {{0,0,0},{0,0,0},{0,0,0}};
Just a {} is enough ;).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.