Click here for important information about

return 2D array

August 4, 2010 at 14:07:30
Specs: Windows XP
In my program, I declare a 2-dimensional array, and I then want to create a function that returns it so I can access it elsewhere. I've never been good at pointers, though, and I'm having a hard time figuring out how to do this. Here's basically what I have:
GLdouble objectMatrices[6][16];

void something(){
   //set values in objectMatrices

GLdouble** getObjectMatrices(){
  return objectMatrices;

I know something is wrong with this last function - the return type? I'm just really not sure. Any ideas?

See More: return 2D array

August 5, 2010 at 08:08:05
your function is wanting to return a pointer to a pointer, but objectMatrices is a static 2d array. If you're wanting to use this "globally", then it *might* be eaiser just to pass it into any functions as a parameter.

void myfunc(GLdouble (*arr)[16]) {
   ... // do something with array

or maybe

void myfunc(GLdouble arr[][16]) {
   ... // do something with array

GLdouble objectMatrices[6][16];

The two boundaries *should* be declared as consts as well rather than hard coded.

const int NROWS = 6;
const int NCOLS = 16;

If you want to use the pointer, then perhaps something like

GLdouble **myfunc(const int &, const int &);
GLdouble **arr;

arr = myfunc(NROWS, NCOLS);
// do something with arr
for(int i=0; i < NROWS; i++) {
   delete [] arr[i];
delete [] arr;

GLdouble **myfunc(const int &nrows, const int &ncols) {

   GLdouble **tmp = NULL;

   tmp = new GLdouble *[nrows];
   for(int i=0; i < nrows; i++) {
       tmp[i] = new GLdouble[ncols];
   return tmp;

Something like that. HTH

Report •
Related Solutions

Ask Question