Monday, May 24, 2010

I want to create a two dimensional array of integers based on the dimesions that the user provides in C++.?

I get an error from the compiler saying that the value (int array[#][#]) in the brackets must be a const. How can make the integer array based on the dimension the user provides? Statically and dynamically (with new int)

I want to create a two dimensional array of integers based on the dimesions that the user provides in C++.?
Dynamically with new int[value]. Statically, you need to know the values at compile time.





First, get your x and y values from the user.


Then:





int ** arr=new int*[y];


for(int i=0; i %26lt; y; i++)


{


arr[i]=new int[x];





}
Reply:When you create an array on the stack (int someArr[DIM_ONE][DIM_TWO]) the size must be known at compile time, which means the integers must be constant. This means that the only way you can create an array of variable size is to do so on the free store.





Hence you’ll have to do something like int *someArr = new int[dimOne][dimTwo]. Be careful with the pointer. Remember to free the memory up.





EDIT: My mistake. Yes, TreyJ is correct. You can't do [][], so you'll have to construct it by multiplying out the dimensions. See the FAQ entry for more details: http://www.parashift.com/c++-faq-lite/fr...
Reply:The compiler I'm using (Visual Studio's C++) doesn't support non-constant arrays, so the example given by the previous person doesn't work. I couldn't find a way to do it using [x][y], but I did find a way using a single-dimention array if you don't mind computing the offset manually. Here's my example for you that creates a 3 x 5 array of integers, fills it, and then displays the values:





#include %26lt;stdio.h%26gt;





void main()


{


int *a = NULL;


int Dim1, Dim2;


int i, j;





Dim1 = 3;


Dim2 = 5;





a = new int[Dim1*Dim2];





for ( i = 0; i %26lt; Dim1; i++ ) {


for ( j = 0; j %26lt; Dim2; j++ ) {


a[i*Dim2 + j] = (i+1) * (j+1);


}


}





for ( i = 0; i %26lt; Dim1; i++ ) {


for ( j = 0; j %26lt; Dim2; j++ ) {


printf( "Value at (%d,%d) which is %d*%d: %d\n", i, j, i+1, j+1, a[i*Dim2 + j] );


}


}


delete [] a;


a = NULL;


}





which gives the output:





Value at (0,0) which is 1*1: 1


Value at (0,1) which is 1*2: 2


Value at (0,2) which is 1*3: 3


Value at (0,3) which is 1*4: 4


Value at (0,4) which is 1*5: 5


Value at (1,0) which is 2*1: 2


Value at (1,1) which is 2*2: 4


Value at (1,2) which is 2*3: 6


Value at (1,3) which is 2*4: 8


Value at (1,4) which is 2*5: 10


Value at (2,0) which is 3*1: 3


Value at (2,1) which is 3*2: 6


Value at (2,2) which is 3*3: 9


Value at (2,3) which is 3*4: 12


Value at (2,4) which is 3*5: 15


No comments:

Post a Comment