multi dimensional array of pointers

i want to create a multi dimensional array which can store address of different variables. please tell how to do that??
You need to say more. How many dimensions? What type of variable?
I want a two dimensional array to store the addresses of integer type variables.
Here's an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main()
{
  int* a[2][3]; //2 rows, each row with 3 columns

  //allocate memory and initialize each pointed element
  a[0][0] = new int(0);
  a[0][1] = new int(1);
  a[0][2] = new int(2);
  a[1][0] = new int(3);
  a[1][1] = new int(4);
  a[1][2] = new int(5);

  //destroy all pointed elements and deallocate their memory
  for (int i = 0; i < 2; ++i)
    for (int j = 0; j < 3; ++j)
      delete a[i][j];
}
But you need some solid reference (a book probably) for such things.

Regards
Hi ,
What will we do if we want to do using only pointer .( constructor of the two dimensional array ?
actually i have a class which has a public integer type variable 'input', and a global array (for storing the address).now when constructor is called a data is stored in input and the address of input is stored in global array. but when i am trying it to dereference the data from sum another function it's is showing some garbage value....what can be the problem ?
@bluecoder
If you want to dynamically allocate the array, you can use
1
2
3
4
5
6
7
8
9
10
11
  int m = 2;
  int* (* a)[3] = new int*[m][3]; //m rows, each row with 3 columns

  //allocate memory and initialize each pointed element
  //... as before

  //destroy all pointed elements and deallocate their memory
  //... as before

  //destroy the dynamically allocated array
  delete[] a;
Notice two things. First, the second dimension is fixed in compile time. With gcc's non-standard extensions you can do something like int* (*a)[n] = (int* (*)[n])new int*[m * n]; to get around the issue. Also, you can always perform you own index arithmetic, like i * n + j, albeit at some cost of readability. The next standard will support variable sized arrays, and this may be fixed, although I am not sure. Notice that you can not initialize the members of the array with aggregate initializer (in curly braces) during the allocation. This will also be fixed in the next standard (I believe).

@satyamkrishna2004
It doesn't appear that you are doing something wrong from your description. May be the problem is algorithmic, not technical. Still, you should ensure to deallocate the constructed objects that host the integers ONLY AFTER you stop using the pointer array. Otherwise the pointers you dereference would point to deallocated memory.

Regards
Topic archived. No new replies allowed.