Reputation: 35
When using the code below, it sets the x value of the Tile objects to i and the y value to j. But if I print the values only the y value is correct, the x value is always 4095.
Code:
Main code:
Tile * tiles = new Tile[4096,4096];
for(int i = 0; i< 4096;i++)
{
for(int j = 0;j< 4096;j++)
{
tiles[i,j].x = i;
tiles[i,j].y = j;
}
}
for(int i = 0; i< 4096;i++)
{
for(int j = 0;j< 4096;j++)
{
cout << "X (Should be " <<i<<"): "<< tiles[i,j].x << " " << "Y (Should be " <<j<<"): "<< tiles[i,j].y << "\n";
}
}
Tile.h:
#pragma once
class Tile
{
public:
int x, y;
};
Upvotes: 2
Views: 137
Reputation: 22157
You are not using arrays right:
i,j
will always return j
, as that is the result of comma operator.
Tile** tiles = new Tile*[4096];
for(int i = 0; i < 4096; i++)
tiles[i] = new Tile[4096];
for(int i = 0; i< 4096;i++)
{
for(int j = 0;j< 4096;j++)
{
tiles[i][j].x = i;
tiles[i][j].y = j;
}
}
for(int i = 0; i< 4096;i++)
{
for(int j = 0;j< 4096;j++)
{
cout << "X (Should be " <<i<<"): "<< tiles[i][j].x << " " << "Y (Should be " <<j<<"): "<< tiles[i][j].y << "\n";
}
}
// Destruction! DON'T FORGET!
for(int i = 0; i < 4096; i++)
delete[] tiles[i];
delete[] tiles;
If you calculate values from comma operator, your original code would be:
Tile * tiles = new Tile[4096]; // returned last 4096
for(int i = 0; i< 4096;i++)
{
for(int j = 0;j< 4096;j++)
{
tiles[i,j].x = i; // the same as tiles[j].x = i;
tiles[i,j].y = j; // the same as tiles[j].y = j;
}
}
///...
Upvotes: 10