-3

To get the position of an array in c++ you can do the following:

class Slot
{
public:

    int Color;
    std::string name;
    /*.... more properties*/
};

int main()
{
    Slot pix[60];

    Slot& randomSlot = pix[12];
    randomSlot.Color = 12;
    randomSlot.name = "sdsd";

    Slot* addressOfSlot = &randomSlot;
    Slot* arrayStart = pix;

    //get the original pos
    int x = addressOfSlot - arrayStart;
}
  1. how would you do it to get the x and y positions of a 2d array like this? :

    Slot pix[60][21];
    

I want to use this approach because I'm gonna be working with pointers/references and I would like to have a fast approach to get the original position,

  1. Also can you do this in c# with unsafe code or something similar?
crashmstr
  • 28,043
  • 9
  • 61
  • 79
elios264
  • 384
  • 4
  • 19
  • how would you represent [30][30]? Are you trying to get the 1d position of a 2d position? – NathanOliver Oct 12 '15 at 18:12
  • Are you saying that given a value, you want to find its indicies in the array? – Ron Beyer Oct 12 '15 at 18:13
  • @NathanOliver the same way its represented in C# `byte[,] myArray`, Im sure is continuous memory in c#, Im looking to do this in c# but c++ was the only way to explain the problem. [Two-dimensional array in memory](http://stackoverflow.com/questions/11575735/two-dimensional-array-in-memory) – elios264 Oct 12 '15 at 18:16
  • @RonBeyer that's correct. – elios264 Oct 12 '15 at 18:17
  • 1
    In C# at least, given that you want an O(1) lookup, a better data structure would be a hash table or dictionary. If the X/Y is important, you can store that along with the value as a Tuple. – Ron Beyer Oct 12 '15 at 18:18
  • to find index of array refer: http://stackoverflow.com/questions/3909784/how-do-i-find-a-particular-value-in-an-array-and-return-its-index – vishal Oct 12 '15 at 18:21

1 Answers1

1

You can map from a 2D array of size ROWS x COLS to a 1D array of the same size and vice versa via

array2D[x][y] <-> array1D[x * COLS + y];

where COLS is the number of columns. This uses the fact that in C or C++ the arrays are stored in what's technically called row-major order. Fortran or MATLAB use column-major order, so the indexing is transposed.

vsoftco
  • 55,410
  • 12
  • 139
  • 252