# multi dimensional array in openFrameworks

Hi,

I am trying to move my code from Processing to OF at the moment but got stuck when I translate multi-dimentional array class with constructors.

In Processing my code is like this:

``````

aClass[][] myClass= new aClass[numX][numY];

...

void setup(){
...
for(int j=0; j<numY; j++) {
for(int i=0; i<numX; i++) {
...
myClassl[i][j]= new aClass(i,j,x,y);
}
}
}

void draw(){
for (int j=0; j<numY; j++){
for(int i=0; i<numX; i++){
myClass[i][j].display();
}
}
}

``````
``````

class aClass{
...
aClass(int _i, int _j, int_x, int_y){
i= _i;
j= _j;
x= _x;
y= _y;
}

void display(){

}
}

``````

How can I translate it to OF language?
I went through the nice tutorial on wiki ( http://wiki.openframeworks.cc/index.php-…-2B-Classes ) and had a piece of ideas of pointers but it currently finish at single array. I need one more step!

If anyone could help me, I really really appreciate.

have a look here:

http://forum.openframeworks.cc/t/arrays-for-c+±newbies/918/0

I think it´s already answered in the link m9dfukc posted, but use vector<> from STL. It´s simpler and easier to use, unless you have a good reason to use dynamically allocated arrays in this case.

vectors are nice, but it is useful to understand arrays, and it’s easier than you might think.

This was also covered in that other thread, but to give you a specific example…
I generally like to simplify an n-dimensional array to 1-dimensional, you just have to multiply the dimensions to get the total size of your 1d array:

``````

aClass[][] myClass= new aClass[numX][numY];

``````

becomes:

``````

aClass * myClass = new aClass[numX*numY];

``````

then to index the array properly, you use the following formula:
index = xIndex+yIndex*xSize

so the rest of your code would be:

``````

void setup(){
...
for(int j=0; j<numY; j++) {
for(int i=0; i<numX; i++) {
int index = i+j*numX;
myClassl[index]= new aClass(i,j,x,y);
}
}
}

//for the draw function, we don't care about the i and j values individually,
//so we only need one loop
void draw(){
for(int i=0; i<numX*numY; i++){
myClass[i].display();
}
}

``````

Thanks for your help m9dfukc, AinSoph and Tim S and sorry for my late reply.

I took the way of using 1d array as well as trying Vector, then solved the problem. I guess these two ways are much easier and more convenient than making multi-dimensional arrays unless there is any specific needs to use the multi one. In my case, changing to 1d array was enough to solve the problem.

Thanks again, I could complete my project! You really saved me!