0

I am a bit of a C++ newbie and I am working on a project and I a little stuck. I need to create a dynamic 2D ragged array then have a pointer point to it. Here is what I have:

int ** x = new int*[3];
int *** y = ???;

Now, after I do:

x[n] = new int[length];
x[++n] = new int[length2];
//etc etc

I can access the values in the array through a statement like:

int num = x[i][j];

What I want is to be able to the same array values through y like:

int num2 = *y[i][j];

So, in this case, num2 and num should have the same value, how would I go about allocating the memory for y and assigning it?

Thanks!

reconrey
  • 129
  • 1
  • 2
  • 7
  • 3
    As a "C++ newbie", do yourself a favor and forget that you ever even heard of `new`, especially the array form of `new`. For a ragged 2D array, use `std::vector>`. – Jerry Coffin Sep 10 '14 at 18:45
  • The project is for a class and the design spec indicates that that we are not to use vectors. – reconrey Sep 10 '14 at 18:50
  • Then fire your teacher and find one who has a clue what's he's doing. Sorry to be so blunt, but this is utterly inexcusable behavior on his part. – Jerry Coffin Sep 10 '14 at 18:53

2 Answers2

0

A pointer to x would be:

int *** y = &x;

There is no need to allocate space for y.

Carl
  • 993
  • 8
  • 14
  • Doesn't that make y point to x? I want y to point to a pointer that is pointing to what x is pointing to – reconrey Sep 10 '14 at 18:54
0

Here is an example of creating a 2D array in C++.

#include <iostream>

int main() {
  // dimensions
  int N = 3;
  int M = 3;

  // dynamic allocation
  int** ary = new int*[N];
  for(int i = 0; i < N; ++i)
      ary[i] = new int[M];

  // fill
  for(int i = 0; i < N; ++i)
    for(int j = 0; j < M; ++j)
      ary[i][j] = i;

  // print
  for(int i = 0; i < N; ++i)
    for(int j = 0; j < M; ++j)
      std::cout << ary[i][j] << "\n";

  // free
  for(int i = 0; i < N; ++i)
    delete(ary[i]);
  delete [] ary;

  return 0;
}

// OUTPUT
0
0
0
1
1
1
2
2
2

Check this answer too for more.

So now, you have created the 2D array. You want just a pointer to point to it. You do not need to allocate memory again (this would be wrong)!

So, you just need to do something like this:

  int ***p = &ary;

  // print
  for(int i = 0; i < N; ++i)
    for(int j = 0; j < M; ++j)
      std::cout << (*p)[i][j] << "\n";

...but wait, it's C++! You should use std::array or std::vector instead of primitive arrays (expanding them for 2D, like std::vector< std::vector >)!

Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305