# multi dimensional array c++

## Recommended Posts

Does #define IX(i,j) ((i)+(*N+2)*(j)) create a multidimensional aray in c++?

No.

##### Share on other sites
so what would i get if i set x[IX(2,2)]=2?
would i get x[4]=2 or?

##### Share on other sites
x[IX(2,2)] is not x[4], because N isn't defined; IX also does not create anything, as it's a mathematical function to find the element in a 2D array given the row and column the element resides:

Assuming "x" is a pseudo-multi-dimensional array (i.e., is a contiguous 1D array), then no; the code will not work as expected since N is not defined:

#define IX(i,j) ((i)+(*N+2)*(j))int width = 8;int height = 6;int* x = new int[ width * height ];x[ IX(2, 3) ] = 1;// expands to:// x[ 2+(*N+2)*3 ] = 1;// error: N is not defineddelete[] x;

What you probably want is:
#define IX(x,y,width)  ((x)+width*(y))int width = 8;int height = 6;int* x = new int[ width * height ];x[IX(2,3,width)] = 2;delete[] x;

##### Share on other sites
What i want is to be able to find a specified value at a given row and column in a dim(A)=64 where A is a matrix.

So basically i want to access the values in a matrix like in Matlab if you know what that is :P

##### Share on other sites
Quote:
 Original post by tompishWhat i want is to be able to find a specified value at a given row and column in a dim(A)=64 where A is a matrix.So basically i want to access the values in a matrix like in Matlab if you know what that is :P

The second example by _fastcall shows you how to allocate, access, and delete the matrix. Did you try the code to see how it works?

##### Share on other sites
If you can set the array size ahead of time and leave it that way, then just create a 2-dimensional array.

Otherwise, use boost::multi_array. Don't try to do your own memory management. Doing the necessary memory management work is a lot harder than the stuff you've already shown yourself not to understand, and there's no point to it, anyway: it can't really be done more efficiently than the library code does it.

##### Share on other sites
i ran the #define IX(i,j) ((i)+(*N+2)*(j)) because in my program i define N later on and now everything seems to work.

tx for the help guys

##### Share on other sites
Why did you ask if you apparently aren't interested in taking any advice?

##### Share on other sites
Quote:
 Original post by tompishi ran the #define IX(i,j) ((i)+(*N+2)*(j)) because in my program i define N later

Why is N, the width of the matrix, a pointer? Why are you adding two to the width of the matrix?

##### Share on other sites
I Have a class defined for handling the arrays so i use a pointer. And i looked in to all the advice and descided to not change my code too much because i allready found what was wrong in the first place. I appreciate all the help.

## Create an account

Register a new account

• ## Partner Spotlight

• ### Forum Statistics

• Total Topics
627682
• Total Posts
2978622

• 9
• 14
• 12
• 10
• 12