1 Replies - 497 Views - Last Post: 10 August 2016 - 09:17 AM Rate Topic: -----

#1 porkinspullup   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 20
  • Joined: 06-January 14

Converting 2D C++ array/matrix constructor to Java

Posted 10 August 2016 - 08:50 AM

Hello everyone. I am having some trouble trying to port a constructor in a code library from C++ to Java. I am not very familiar with pointers in C++. In the code there is a double with two *s on it, indicating that it is a dereference to a reference.
 double **data;

And then further down in the code there is a constructor that creates and fills a 2D array matrix using the double data above
    //! @brief Resize constructor
    //!
    //! @param r The number of rows in the new matrix
    //! @param c The number of columns in the new matrix
    //!
    matrix (int r, int c)
    {
      int y, x;
      rows = r;
      cols = c;
      valid = true;

      data = new double*[rows];
      for (y = 0; y < rows; ++y)
      {
        data[y] = new double[cols];
        for (x = 0; x < cols; ++x)
        {
          data[y][x] = 0.0f;
        }
      }
    }

This line in particular
data = new double*[rows];

I don't really understand. I am wondering not only what the pointers indicate in this piece of code but also what the Java equivalent of it would be. Thanks for any help you guys can provide.

Is This A Good Question/Topic? 0
  • +

Replies To: Converting 2D C++ array/matrix constructor to Java

#2 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7253
  • View blog
  • Posts: 15,126
  • Joined: 16-October 07

Re: Converting 2D C++ array/matrix constructor to Java

Posted 10 August 2016 - 09:17 AM

The double **data; is an array of arrays. Also called a "jagged" 2d array, as there's no real guarantee that the arrays in the array will be the same size.

Curiously, Java's 2D array is basically the same thing. A quick google of "java array 2d" reveals pages of hits to answer your question...

If you think about it in 1D, the java equivalent to double *xs = new double[size]; is double[] xs = new double[size];. In 2D, the java equivalent to double **xs = new double*[size]; is double[][] xs = new double[size][];. Though, there is better syntax for java than that.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1