multi dimensional array of pointers

Mar 2, 2011 at 3:27pm
i want to create a multi dimensional array which can store address of different variables. please tell how to do that??
Mar 2, 2011 at 4:19pm
You need to say more. How many dimensions? What type of variable?
Mar 3, 2011 at 7:38am
I want a two dimensional array to store the addresses of integer type variables.
Mar 3, 2011 at 8:17am
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
Mar 3, 2011 at 9:15am
Hi ,
What will we do if we want to do using only pointer .( constructor of the two dimensional array ?
Mar 3, 2011 at 10:01am
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 ?
Mar 3, 2011 at 11:01am
@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.