Aug 15, 2011 at 11:15pm UTC
I am having trouble figuring out how to create a 4D matrix in c++ with only one variable, and 3 constant dimensions.
I am trying to create the matrix
B[n_elements][n_shape_functions][n_integration_stations][n_dimensions]
where n_elements is read in from a file, while all the rest are hard-coded as constant.
I assume dynamic allocation is necessary, but I am not sure how to approach this.
(For reference, I use a Mac and code in Xcode)
Thanks!
Aug 15, 2011 at 11:21pm UTC
Use the STL to your advantage: use a deque or vector . You can initialize the size of any of them.
Aug 16, 2011 at 6:01pm UTC
I'm a beginner with c++, I haven't learned about stl yet. Do you have a suggestion for a good reference to learn the ins and outs of it?
Aug 16, 2011 at 6:37pm UTC
Hi,
Please try this and tell me if it works for you
* To create the array
int (*pointer)[n_shape_functions][n_integration_stations][n_dimensions] = new int [readValueFromFile][n_shape_functions][n_integration_stations][n_dimensions];
* To use the array you need to do something like this:
1 2 3 4 5
for (i=0; i<readValueFromFile; i++){
for (j=0; j<n_shape_functions; j++)
for (k=0; k<n_integration_stations; k++)
for (l=0; l<n_dimensions; l++)
pointer[i][j][k][l]=0;
Last edited on Aug 16, 2011 at 6:44pm UTC
Aug 16, 2011 at 6:49pm UTC
Seems to work fine. THANKS SO MUCH!
Aug 16, 2011 at 7:18pm UTC
I learned something amazing!
Aug 16, 2011 at 7:53pm UTC
One last step!! Don.t forget to release the dynamically allocated memory when you are done with it else a memory leak results.
delete [] pointer;
I wrote a complete program to post here but it uses the same method that gaorozcoo presented.
Oops, too late!
Aug 16, 2011 at 7:57pm UTC
Thanks for all the "pointers" everyone. (Had to do it.)
I appreciate the help!
Aug 18, 2011 at 8:40pm UTC
Update: I've been using this constantly in my code. This is so much easier that what I had been doing!