I find your work around very good idea. Thanks Carlos. On May 15, 2012, at 9:30 PM, Carlos Guia wrote:
> Depends on your exact needs, if all you care about is accessing elements as > mat[i][j] you can do something like this: > > > int** matrix; > ... > matrix = new int*[M]; // create an array of pointers to int > for (int i = 0; i < M; ++i) > matrix[i] = new int[N]; // create an array of integers for each "row" > > // now matrix[i][j] should work as expected > // you can free memory like this > for (int i = 0; i < M; ++i) > delete[] matrix[i]; // delete each array of integers > delete[] matrix; // delete the array of pointers > > > Creating that way, is simple and intuitive, but has the disadvantage that the > elements are not contiguous in the matrix, each row has it's elements > contiguous, but not the complete matrix. That means, that a function that > expects a "normal" matrix and uses the fact that something like "int > mat[3][4]" has the 12 values contiguous may break. > > A work around for that is to create the contiguous array of size MxN and then > assign the correct pointers, something like: > int** matrix; > ... > int* temp = new int[M * N]; // contiguous array for the integers > matrix = new int*[M]; // create an array of pointers to int > for (int i = 0; i < M; ++i) > matrix[i] = temp + N * i; // Make each element of "matrix" point to the > start of the corresponding row > // NOTE: DO NOT DELETE temp, for extra safety, make it a null pointer > temp = 0; > > // now matrix[i][j] should work as expected, also, all elements are > contiguous > // you can free memory like this > delete[] matrix[0]; // delete the contiguous array of integers > delete[] matrix; // delete the array of pointers > > You can extend this idea for any number of dimensions you like. > > Regards, > Carlos Guía > > > On Tue, May 15, 2012 at 8:18 AM, Registered user <[email protected]> > wrote: > how to create 2d or 3d array dynamically , giving the size at run time : for > global array.... > > -- > You received this message because you are subscribed to the Google Groups > "Google Code Jam" group. > To post to this group, send email to [email protected]. > To unsubscribe from this group, send email to > [email protected]. > For more options, visit this group at > http://groups.google.com/group/google-code?hl=en. > > > -- > You received this message because you are subscribed to the Google Groups > "Google Code Jam" group. > To post to this group, send email to [email protected]. > To unsubscribe from this group, send email to > [email protected]. > For more options, visit this group at > http://groups.google.com/group/google-code?hl=en. -- You received this message because you are subscribed to the Google Groups "Google Code Jam" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/google-code?hl=en.
