-1

One of my favorite things to do in JavaScript is mess around with multi-dimensional arrays. I decided to learn C++, and I wanted to try and mess around with arrays to help me learn it. I made my very first C++ program turn a multi-dimensional array into a text based table. It was very complicated and took me a few hours to figure out, mainly because arrays in JavaScript are a lot different from arrays in C++. My program will turn an array like this:

int a[5][4] = {{44,0,1, 55555555}, {144,2,44444, 67}, {2,444,6, 99}, {3,44,7, 2}, {4,8,9444, 1000}};

into this:

--------------------------------
| 44  | 0   | 1     | 55555555 |
|-----+-----+-------+----------|
| 144 | 2   | 44444 | 67       |
|-----+-----+-------+----------|
| 2   | 444 | 6     | 99       |
|-----+-----+-------+----------|
| 3   | 44  | 7     | 2        |
|-----+-----+-------+----------|
| 4   | 8   | 9444  | 1000     |
|------------------------------|

What confuses me is that when I do not initialize my array e.g. int a[5][4];, my table comes out like this:

-------------------------------------------
| 1          | 0     | 1606416280 | 32767 |
|------------+-------+------------+-------|
| 0          | 1     | 0          | 0     |
|------------+-------+------------+-------|
| 1606416296 | 32767 | 0          | 0     |
|------------+-------+------------+-------|
| 0          | 0     | 0          | 0     |
|------------+-------+------------+-------|
| 0          | 0     | 0          | 0     |
|-----------------------------------------|

where are these random numbers coming from?

Note: these numbers do not come from my code because when I create a new project and just add the declaration of the array int a[5][4] and then cout << a[0][2];, I get the number 1606416280 in the console.

Mashpoe
  • 504
  • 1
  • 9
  • 27

3 Answers3

1

In C++, stack variables are not initialized, so the number you are outputting is whatever value was stored at that memory address before(some random garbage value).

user3147395
  • 541
  • 3
  • 7
0

Printing uninitialised variables is invoking undefined behavior. In your own words:

these numbers do not come from my code

You are correct - they are garbage values. To overcome, you must assign some values and then print out these values. However that being said, please note that global variables are always initialized to 0, as pointed out in this SO question.

Community
  • 1
  • 1
0

What confuses me is that when I do not initialize my array e.g. int a[5][4];, my table comes out like this:

In C/C++ a non initialized area of memory is considered garbage. You printed a non initialized area of memory i.e. you printed garbage.

Harry
  • 11,298
  • 1
  • 29
  • 43