Tuesday, July 28, 2009

C++ please?

ok the questions is:


i wanna create a two dimentional array...but i want the user to decide the size of the array...


when i write for example


cin%26gt;%26gt;x;


int mr[x][x];


i get a syntax error...so it doesnt wrok like that...


what should i do ?


create a function for it or what...??

C++ please?
//start of code


cin %26gt;%26gt; n; // size of array (square array)





double* X = new double [ n ];


double** F = new double* [ n ];


F [ 0 ] = new double [ n * n ];


for ( int i = 1 ; i %26lt; n ; i++ )


{


F [ i ] = F [ i - 1 ] + n;


}


//end of code





The above is a method that initializes a horizontal vector (1*N) of pointers, and then each pointer is used as a vertical vector (N*1). Thus, you will get a 2D dynamically allocated array.


I learnt this in the "Numerical Analysis Lab." at college





hope that helped!
Reply:I've had this problem too.


Since your using C++ (right?), you can use the new operator.





int *a, x, y;


cin%26gt;%26gt;x%26gt;%26gt;y;


a=new int[x][y];





And "a" is a new multidimensional array!


I have a snippet of code that proves it works, but I'm not working from that computer.
Reply:If you are creating anything at runtime ( you mention that the user decides the size ), then you will need to create the memory dynamically.





The syntax you have given "int mr[x][x];" is incorrect as this is static memory allocation, and this must be determined at compile time.





You have a few options:


1. Create the memory dynamically


2. Use an array storage mechanism





Option 1:


int x = 10; // The first Dimension of the array


int y = 12; // The second Dimension of the array





// Create the memory


int *pmr = (int)malloc( sizeof( int ) * ( x * y );





// Access the elements ( you need to do a bit of maths as the array is actually a single dimension, but big enough to hold the 2 dimensions.


// e.g. to access mr[2][3]


int value = *(pmr + ( 3 * x ) + 2 );





// Clear it down when you have finished


free(mr);








Option 2:


Look at the "vector" from STL.


#include %26lt;vector%26gt;


...


vector%26lt;int%26gt; vInts;


vInt.push_back(2)








[Please excuse any mistakes]
Reply:I know in VB that would be easy with the "redim" function. but I dont think C++ natively handles dynamic arrays. In that syntax, the compiler needs to know what 'X' is before execution to know how much memory to allocate to the array. Thats where the error is coming from.





To change the size of an array during runtime you'll probably have create an array (lets say of 1 x 1 to start) and then use the C functions "malloc" and "realloc" to change its size. Look up those functions, I havent used em in far too long but I know its not simple


No comments:

Post a Comment