开发者

How to implement an algorithm with pointers and memory allocation in Java

I have an algorithm in C++ and I need to implement something similar in Java. I'm having trouble with memory alloca开发者_JAVA百科tion. How can I migrate the following snippet for example, from C++ to Java?

size_x = 3; size_y = 6; 
double **Data, *pDataData;
Data = (double **)malloc(size_x*sizeof(double *)+size_x*size_y*sizeof(double));
for (i = 0, pDataData = (double *)(Data+size_x); i < size_x; i++, pDataData += size_y)
Data[i]=pDataData;

I know that for a simple malloc like: char *x = (char *) malloc(256); In Java, I would say: ByteBuffer x = ByteBuffer.allocate(250);

For anything more complicated, I get confused.

Thank you in advance


That's a 2 dimensional array.

double Data[][] = new double[size_x][size_y];


Short answer: It is neither necessary nor desirable to do such a thing in Java or in C++. Since the invention of classes, when you need a complex structure, you should create a class, not allocate an amorphous blob of memory and then put things in that memory that are retrieved by an offset rather than a name.

So it looks like you're trying to allocate an array of size_x of pointers to doubles, and then a two-dimensional array of size size_x by size_y of doubles, with the pointers pointing to successive rows in the table? Sorry if I'm not understanding what you're trying to do. This is exactly why the Java way is, in my humble opinion, superior: Complex structures are not that hard to figure out.

In Java, there would be no need to have the pointers to the rows. So in Java this would just turn into:

public class MyDataData
{
  double[][] table;

  public MyDataData(int size_x, int size_y)
  {
    table=new double[size_x][size_y];
  }
}

To invoke it you'd just write

MyDataData whatever=new MyDataData(3,6);

And that would be about it. If you need a reference to a row, you'd just get table[x].

Don't try to simulate malloc in Java. That's not how it's done. Just define the class you need and use "new" to make one, and Java will worry about allocating the memory for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜