I’m new to C++, and I think there’s some concept I’m missing because all I’m trying to do is set a value in a 2d array and it’s messing up. Instead of just setting it once in the location I specify, it sets it in multiple locations. The code makes perfect sense in other languages, so it must be some quirk of C++ that I don’t know?
#include <iostream>
#include <string>
int main()
{
const int width=26;
const int height=10;
char arr[width][height];
//fill with dots
std::string empty=".";
for (int i=0;i<height;i++)
{
for (int j=0;j<width;j++)
{
arr[i][j]=empty[0];
}
}
std::string msg="test";
//set location row=5, col=3 to "t"
arr[5][3]=msg[0];
//print the array
for (int i=0;i<height;i++)
{
for (int j=0;j<width;j++)
{
std::cout<<arr[i][j];
}
std::cout<<std::endl;
}
}
The result is:
..........................
..........................
..........................
.......................t..
............t.............
...t......................
..........................
..........................
..........................
..........................
There should only be 1 t in the middle. I don’t understand why it’s putting the other 2 t’s.
By the shape of the output, you’re obviously using height of 10 and width of 26.
You are referencing the array as
[i][j]whereiis vertical andjis horizontal, but in that case the array is defined with 26 rows and 10 columns. So you are overflowing it when you print out. The array is just a contiguous block of memory, so this isn’t overflowing that block. Otherwise you’d have a crash. But it is incorrect.Your rows are currently 10 chars long but you are accessing as if they are 26. This means you take values from the next 2 rows. The extra ‘t’ values in the output are the result of overflowing in the rows before them.
Hope this makes sense.
Either change the accesses to
arr[j][i], or the definition tochar arr[10][26].