2

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;
};
Magnus Hoff
  • 21,529
  • 9
  • 63
  • 82
  • I'm not sure what you are trying to do with `Tile[4096,4096];` and all the similar accesses, but I'm sure it doesn't do what you meant. You are falling foul of the [comma operator](http://en.wikipedia.org/wiki/Comma_operator), and basically doing `Tile[4096];`. If you want a 2d array, you need to use 2 sets of square brackets, and with `new` it's a bit fiddly: http://stackoverflow.com/questions/936687/how-do-i-declare-a-2d-array-in-c-using-new – BoBTFish Aug 22 '13 at 07:51
  • Do you have any pressing reason to use raw (c++-style) arrays? If not that then I would strongly suggest using `std::vector` instead. – Grizzly Aug 22 '13 at 08:07

1 Answers1

10

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;
        }
    }

///...
Nemanja Boric
  • 21,627
  • 6
  • 67
  • 91
  • When trying to compile "Tile * tiles = new Tile[4096][4096];", I'm getting this error: 2 IntelliSense: a value of type "Tile (*)[4096]" cannot be used to initialize an entity of type "Tile *" – user1990950 Aug 22 '13 at 07:52
  • @user1990950 See the link on my comment to the question. – BoBTFish Aug 22 '13 at 07:53